gpt4 book ai didi

javascript - 如何将此 json 转换为 C# 对象

转载 作者:太空宇宙 更新时间:2023-11-03 19:45:31 26 4
gpt4 key购买 nike

我从第三方收到这个 JSON,因此无法控制它,

{
code: 200,
message: success,
data: {
categories: {
0: {
prop1: 100,
prop2: blah
},
1: {
prop1: 100,
prop2: blah
}
// etc.. etc.. it may return around 100 or more categories or less
}
}
}

现在我正在尝试将其转换为 C# 对象,

[DataContract]
public class Category
{
[DataMember] public string prop1 { get; set; }
[DataMember] public string prop2 { get; set; }
}

[DataContract]
public class Data
{
[DataMember]
public List<Category> categories { get; set; }
}

[DataContract]
public class RootObject
{
[DataMember]
public int code { get; set; }
[DataMember]
public string message { get; set; }
[DataMember]
public Data data { get; set; }
}

和转换它的代码,

   var response = LoadPageAsync(url).Result;
var serializer = new JavaScriptSerializer();
var rootObject = serializer.Deserialize<RootObject>(response);

问题是我得到的类别计数为零,即使 JSON 本身有很多。

最佳答案

您需要将类别列表更改为字典。测试了以下代码,我根据需要实现了反序列化。还值得注意的是,如果字符串周围没有引号,您的 json 实际上是无效。我也使用了 JSON.Net,但这应该无关紧要。

[DataContract]
public class Category
{
[DataMember] public string prop1 { get; set; }
[DataMember] public string prop2 { get; set; }
}

[DataContract]
public class Data
{
[DataMember]
public Dictionary<int, Category> categories { get; set; }
}

[DataContract]
public class RootObject
{
[DataMember]
public int code { get; set; }
[DataMember]
public string message { get; set; }
[DataMember]
public Data data { get; set; }
}

static void Main(string[] args)
{
var root = new RootObject()
{
code = 1,
message = "test",
data = new Data()
{
categories = new Dictionary<int, Category>()
{
{ 0, new Category()
{
prop1 = "cat1prop1",
prop2 = "cat1prop2"
}
},
{ 1, new Category()
{
prop1 = "cat2prop1",
prop2 = "cat2prop2"
}
}
}
}
};
var testJson = "{code: 200,message: \"success\",data: {categories: {0: {prop1: 100,prop2: \"blah\"},1: {prop1: 100,prop2: \"blah\"}}}}";
var json = JsonConvert.SerializeObject(root);
var testConvert = JsonConvert.DeserializeObject<RootObject>(testJson);
}

关于javascript - 如何将此 json 转换为 C# 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46292884/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com