繁体   English   中英

C# - 如何将 json 字符串转换为类

[英]C# - How convert json string to class

如何将我的 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; }
}

您的模型应该与此类似(对于无效的 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 时猜测您的模型。

您似乎试图以多种不同的方式反序列化,但您没有完整的结构来实际匹配 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 看起来是一样的。 尽管我必须说这只会帮助您进行反序列化。

首先, $id"属性是Json.NET添加的合成属性,用于跟踪和保存对同一个对象的多个引用。具体参见PreserveReferencesHandling设置

因此,如果您暂时删除"$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<T>反序列化为具体类型的内置逻辑,因此我不得不将该属性保留为public List<CommentDtoAdmin> list { get; set; } public List<CommentDtoAdmin> list { get; set; } public List<CommentDtoAdmin> list { get; set; } . 你总是可以使用AsQueryable()从列表中生成一个可查询的:

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

样品小提琴

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM