【问题标题】:C# - How convert json string to classC# - 如何将 json 字符串转换为类
【发布时间】:2016-10-02 18:47:23
【问题描述】:

如何将我的 json 字符串转换为类

这是我的 json

{
    "$id": "1",
    "Result": {
        "$id": "2",
        "dateTime": 23821964,
        "list": [{
            "$id": "3",
            "UserId": 302,
            "UID": "302_UID",
            "Title": "شیدکو",
            "Sender": "شیدکو",
            "Answer": "",
            "Comment": "test 2",
            "ProductTitle": null,
            "CommentId": 77,
            "Logo": "http://example.com/Commercial/User/302/Logo/tmpF0BF.jpg",
            "Date": 24302057,
            "AnswerDate": -2123661683,
            "AnswerEdit": false,
            "CommentEdit": false,
            "ForfeitCount": 0,
            "RewardCount": 0,
            "ThisCountReport": 2,
            "Reported": [{
                "$id": "4",
                "BlockerId": 355,
                "Title": "محتوای غیر اخلاقی",
                "Date": -19527396,
                "ForfeitCount": 0,
                "RewardCount": 0
            }, {
                "$id": "5",
                "BlockerId": 355,
                "Title": "محتوای غیر مرتبط",
                "Date": -19527382,
                "ForfeitCount": 0,
                "RewardCount": 0
            }],
            "Gem": 0
        }, {
            "$id": "6",
            "UserId": 302,
            "UID": "302_UID",
            "Title": "شیدکو",
            "Sender": "شیدکو",
            "Answer": "",
            "Comment": "test 2",
            "ProductTitle": null,
            "CommentId": 77,
            "Logo": "http://example.com/Commercial/User/302/Logo/tmpF0BF.jpg",
            "Date": 24302057,
            "AnswerDate": -2123661683,
            "AnswerEdit": false,
            "CommentEdit": false

        }]

    },
    "StatusCode": "Created",
    "Description": null
}

我做了这些步骤,但没有任何反应

JObject json1 = JObject.Parse(strMyJson);
    _CommentAdmindto flight = Newtonsoft.Json.JsonConvert.DeserializeObject<_CommentAdmindto>(json1.ToString());
    _CommentAdmindto deserializedProduct = JsonConvert.DeserializeObject<_CommentAdmindto>(json);
    _CommentAdmindto deserializedProduct1 = ConvertJsonToClass<_CommentAdmindto>(strMyJson);
    JsonSerializer serializer = new JsonSerializer();
    _CommentAdmindto p = (_CommentAdmindto)serializer.Deserialize(new JTokenReader(strMyJson), typeof(_CommentAdmindto));

这是我的类和函数:

public static T ConvertJsonToClass<T>( string json)
    {
        System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        return serializer.Deserialize<T>(json);
    }

}

public class _CommentAdmindto
{
    public long dateTime { get; set; }

    public IQueryable<CommentDtoAdmin> list { get; set; }
}

public class CommentDtoAdmin
{
    public long UserId { get; set; }
    public string UID { get; set; }
    public string Title { get; set; }
    public string Sender { get; set; }
    public string Answer { get; set; }
    public string Comment { get; set; }

    public string ProductTitle { get; set; }
    public long CommentId { get; set; }

    public string Logo { get; set; }
    public long Date { get; set; }

    public long AnswerDate { get; set; }

    public bool AnswerEdit { get; set; }

    public bool CommentEdit { get; set; }
}

【问题讨论】:

  • 我想这是一个重复的问题stackoverflow.com/questions/4718888/…
  • @HussainPatel 在你的链接上,他们没有把它添加到课堂上,请看一下
  • 您的 json 与您的模型不匹配

标签: c# json


【解决方案1】:

你的模型应该和这个类似(对于无效的c#名称,你可以使用JsonProperty属性):

public class Reported
{
    [JsonProperty("$id")]
    public string id { get; set; }
    public int BlockerId { get; set; }
    public string Title { get; set; }
    public int Date { get; set; }
    public int ForfeitCount { get; set; }
    public int RewardCount { get; set; }
}

public class List
{
    [JsonProperty("$id")]
    public string id { get; set; }
    public int UserId { get; set; }
    public string UID { get; set; }
    public string Title { get; set; }
    public string Sender { get; set; }
    public string Answer { get; set; }
    public string Comment { get; set; }
    public object ProductTitle { get; set; }
    public int CommentId { get; set; }
    public string Logo { get; set; }
    public int Date { get; set; }
    public int AnswerDate { get; set; }
    public bool AnswerEdit { get; set; }
    public bool CommentEdit { get; set; }
    public int ForfeitCount { get; set; }
    public int RewardCount { get; set; }
    public int ThisCountReport { get; set; }
    public List<Reported> Reported { get; set; }
    public int Gem { get; set; }
}

public class Result
{
    [JsonProperty("$id")]
    public string id { get; set; }
    public int dateTime { get; set; }
    public List<List> list { get; set; }
}

public class RootObject
{
    [JsonProperty("$id")]
    public string id { get; set; }
    public Result Result { get; set; }
    public string StatusCode { get; set; }
    public object Description { get; set; }
}

现在你可以反序列化为

var result = JsonConvert.DeserializeObject<RootObject>(jsonstring);

顺便说一句:http://json2csharp.com/ 在使用 json 时可以帮助猜测您的模型。

【讨论】:

  • 如果您使用的是 Visual Studio 2015,它具有内置的 JSON-to-class 功能。只需打开一个新的空类文件并编辑 > 选择性粘贴 > JSON 作为类。也适用于 XML。并不总是完美但相当不错。在这种情况下,它唯一遗漏的是 ID 变量上的属性装饰。
【解决方案2】:

您似乎试图以许多不同的方式进行反序列化,但您没有完整的结构来实际匹配 json。您错过了外部类(代表完整对象),并且至少 Newtonsoft.Json 无法反序列化为 IQueryable,因此我将其更改为 IEnumerable。

string strMyJson = "{\"$id\":\"1\",\"Result\":{\"$id\":\"2\",\"dateTime\":23826985,\"list\":[{\"$id\":\"3\",\"UserId\":302,\"UID\":\"302_UID\",\"Title\":\"شیدکو\",\"Sender\":\"شیدکو\",\"Answer\":\"\",\"Comment\":\"test 2\",\"ProductTitle\":null,\"CommentId\":77,\"Logo\":\"http://www.domain.com/Commercial/User/302/Logo/tmpF0BF.jpg\",\"Date\":24307078,\"AnswerDate\":-2123656662,\"AnswerEdit\":false,\"CommentEdit\":false,\"ForfeitCount\":0,\"RewardCount\":0,\"ThisCountReport\":2,\"Reported\":[{\"$id\":\"4\",\"BlockerId\":355,\"Title\":\"محتوای غیر اخلاقی\",\"Date\":-19527396,\"ForfeitCount\":0,\"RewardCount\":0},{\"$id\":\"5\",\"BlockerId\":355,\"Title\":\"محتوای غیر مرتبط\",\"Date\":-19527382,\"ForfeitCount\":0,\"RewardCount\":0}],\"Gem\":0},{\"$id\":\"6\",\"UserId\":302,\"UID\":\"302_UID\",\"Title\":\"شیدکو\",\"Sender\":\"شیدکو\",\"Answer\":\"\",\"Comment\":\"test 2\",\"ProductTitle\":null,\"CommentId\":77,\"Logo\":\"http://www.domain.com/Commercial/User/302/Logo/tmpF0BF.jpg\",\"Date\":24307078,\"AnswerDate\":-2123656662,\"AnswerEdit\":false,\"CommentEdit\":false}],\"StatusCode\":\"Created\",\"Description\":null}}";


var result = JsonConvert.DeserializeObject<Wrapper>(strMyJson);

类看起来像这样:

public class Wrapper
{
    public _CommentAdmindto Result { get; set; }
}
public class _CommentAdmindto
{
    public long dateTime { get; set; }

    public IEnumerable<CommentDtoAdmin> list { get; set; }
}

CommentDtoAdmin 看起来一样。 虽然我必须说这只会帮助您进行反序列化。

【讨论】:

  • 谢谢,真的好多了,但我现在有另一个错误,正在处理新错误。System.Web.Extensions.dll 中发生了“System.ArgumentException”类型的异常,但未在用户中处理代码附加信息:“System.Collections.Generic.List1[AdminApp._CommentReported]' cannot be converted to type 'System.Linq.IQueryable1[AdminApp._CommentReported]”类型的对象。
【解决方案3】:

首先,$id" 属性是 Json.NET 添加的合成属性,用于跟踪和保留对同一对象的多个引用。详情请见PreserveReferencesHandling setting

因此,如果您暂时删除"$id" 属性,您可以将您的JSON 上传到http://json2csharp.com/ 并获得以下数据模型:

public class Reported
{
    public int BlockerId { get; set; }
    public string Title { get; set; }
    public int Date { get; set; }
    public int ForfeitCount { get; set; }
    public int RewardCount { get; set; }
}

public class CommentDtoAdmin
{
    public int UserId { get; set; }
    public string UID { get; set; }
    public string Title { get; set; }
    public string Sender { get; set; }
    public string Answer { get; set; }
    public string Comment { get; set; }
    public object ProductTitle { get; set; }
    public int CommentId { get; set; }
    public string Logo { get; set; }
    public int Date { get; set; }
    public int AnswerDate { get; set; }
    public bool AnswerEdit { get; set; }
    public bool CommentEdit { get; set; }
    public int ForfeitCount { get; set; }
    public int RewardCount { get; set; }
    public int ThisCountReport { get; set; }
    public List<Reported> Reported { get; set; }
    public int Gem { get; set; }
}

public class Result
{
    public int dateTime { get; set; }
    public List<CommentDtoAdmin> list { get; set; }
}

public class RootObject
{
    public Result Result { get; set; }
    public string StatusCode { get; set; }
    public string Description { get; set; }
}

然后我将返回的模型修改如下:

  • 我将名称 CommentDtoAdmin 用于 list 类型。
  • 我将Description属性的类型设置为string

现在您的 JSON 可以按如下方式反序列化和重新序列化:

var settings = new JsonSerializerSettings
{
    PreserveReferencesHandling = PreserveReferencesHandling.Objects,
};
var root = JsonConvert.DeserializeObject<RootObject>(json1, settings);

var json2 = JsonConvert.SerializeObject(root, Formatting.Indented, settings);

请注意,Json.NET 没有用于将接口IQueryable&lt;T&gt; 反序列化为具体类型的内置逻辑,因此我不得不将属性保留为public List&lt;CommentDtoAdmin&gt; list { get; set; }。您始终可以使用 AsQueryable() 从列表中生成可查询:

var queryable = root.Result.list.AsQueryable();

示例fiddle

【讨论】:

    【解决方案4】:

    我认为你的 json 字符串没有正确的语法。它看起来像一个']'(数组的结尾)和一个最后的'}'不见了。

    这就是 Visual Studio 编辑器在删除所有 '\' 后从字符串中生成 json 文件时告诉我的内容

    【讨论】:

    • 这不是答案——如果问题有问题,你应该把它放在评论中
    • 我编辑它,json现在工作正常,但我无法得到我所问的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 2021-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多