使用c#反序列化JSON中的值列表
本文关键字:列表 JSON 反序列化 使用 | 更新日期: 2023-09-27 18:16:05
我有两个类使用auto属性:
class B
{
int a { get; set; }
int b { get; set; }
List <A> listofa { get; set; }
}
class A
{
string c { get; set; }
string d { get; set; }
}
我已经反序列化了一个JSON数据源并将数据导入到类中。实际上,我的JSON中有3个类A
对象和一个B
。那么我怎样才能得到我创建的对象的值呢?
我可以通过testOfB.a
(当然是在反序列化之后)得到B类属性的值:
B testOfB = JsonConvert.DeserializeObject<RootObject>(testjson);
但是如何得到testOfB.listofa
的值呢?我确信我应该使用foreach
循环。(我在其他文章中找到了一些例子。)但这些对我都不起作用。我尝试这样做:
foreach(object[] in A)
{
???
}
我接近了吗?任何帮助都会非常感激!!
编辑
这是我要反序列化的JSON:
{
"a": 12,
"b": 13,
"A": [
{
"c": "test",
"d": "test"
},
{
"c": "test2",
"d": "test2"
},
{
"c": "test3",
"d": "test3"
}
]
}
你这里有几个问题:
- 你的成员属性需要是public
- 在你的JSON列表属性被称为
A
,但在你的类它叫listofa
。你要么需要用[JsonProperty("A")]
装饰你的listofa
属性,要么将listofa
重命名为A
,以便它与JSON匹配)。 - 你正在反序列化到一个你没有定义的
RootObject
类。 - 你的
foreach
循环是不对的,正如@billbo指出的。
class B
{
public int a { get; set; }
public int b { get; set; }
[JsonProperty("A")]
public List<A> listOfA { get; set; }
}
class A
{
public string c { get; set; }
public string d { get; set; }
}
class Program
{
public static void Main(string[] args)
{
string json = @"
{
""a"": 12,
""b"": 13,
""A"": [
{
""c"": ""test"",
""d"": ""test""
},
{
""c"": ""test2"",
""d"": ""test2""
},
{
""c"": ""test3"",
""d"": ""test3""
}
]
}";
B testOfB = JsonConvert.DeserializeObject<B>(json);
Console.WriteLine("a: " + testOfB.a);
Console.WriteLine("b: " + testOfB.b);
foreach (A a in testOfB.listOfA)
{
Console.WriteLine("c: " + a.c);
Console.WriteLine("d: " + a.d);
}
}
}
输出:a: 12
b: 13
c: test
d: test
c: test2
d: test2
c: test3
d: test3
您的foreach语句看起来不正确。我会这样写:
foreach(A a in test.listofa)
{
string c = a.c;
string d = a.d;
}