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

时间:2016-10-02 18:47:23

标签: c# json

如何将我的json-string转换为类

这是我的json

{         “$ id”:“1”,         “结果”:{             “$ id”:“2”,             “dateTime”:23821964,             “list”:[{                 “$ id”:“3”,                 “UserId”:302,                 “UID”:“302_UID”,                 “标题”:“شیدکو”,                 “发件人”:“شیدکو”,                 “答案”:“”,                 “评论”:“测试2”,                 “ProductTitle”:null,                 “CommentId”:77,                 “徽标”:“http://www.domain.com/Commercial/User/302/Logo/tmpF0BF.jpg”,                 “日期”:24302057,                 “AnswerDate”:-2123661683,                 “AnswerEdit”:false,                 “CommentEdit”:false,                 “ForfeitCount”:0,                 “RewardCount”:0,                 “ThisCountReport”:2,                 “已报告”:[{                     “$ id”:“4”,                     “BlockerId”:355,                     “标题”:“محتوایغیراخلاقی”,                     “日期”:-19527396,                     “ForfeitCount”:0,                     “RewardCount”:0                 },{                     “$ id”:“5”,                     “BlockerId”:355,                     “标题”:“محتوایغیرمرتبط”,                     “日期”:-19527382,                     “ForfeitCount”:0,                     “RewardCount”:0                 }],                 “宝石”:0             },{                 “$ id”:“6”,                 “UserId”:302,                 “UID”:“302_UID”,                 “标题”:“شیدکو”,                 “发件人”:“شیدکو”,                 “答案”:“”,                 “评论”:“测试2”,                 “ProductTitle”:null,                 “CommentId”:77,                 “徽标”:“http://www.www.domain.com/Commercial/User/302/Logo/tmpF0BF.jpg”,                 “日期”: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; }


    }

4 个答案:

答案 0 :(得分:8)

您的模型应与此类似(对于无效的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);

BTW:http://json2csharp.com/可以帮助您在使用json时猜测您的模型。

答案 1 :(得分:1)

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

if answer1.lower() == "a"

类看起来像这样:

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);

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

答案 2 :(得分:1)

首先,$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<T>反序列化为具体类型的内置逻辑,因此我必须将该属性保留为public List<CommentDtoAdmin> list { get; set; }。您始终可以使用AsQueryable()

从列表中生成可查询对象
var queryable = root.Result.list.AsQueryable();

示例fiddle

答案 3 :(得分:0)

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

在删除所有&#39; \&#39;

后,Visual Studio编辑器在从字符串中创建json文件时告诉我的内容