Csharp/C#教程:使用Json.net将JSON数组中的多个项添加到C#中的对象分享


使用Json.net将JSON数组中的多个项添加到C#中的对象

谁能告诉我如何反序列化包含多个属性的对象?

鉴于下面的场景,代码工作正常。

public ActionResult Index() { string json = @"{""name"": ""Person 2"",""email"": ""example@example.com""}"; var emp = JsonConvert.DeserializeObject(json); Response.Write(emp.name + emp.email); return View(); } public class Person { public string name { get; set; } public string email { get; set; } } 

但是,如果数组包含多个项目,我该怎么做,例如

 string json = @"{""data"": [{""name"": ""Person 1"",""email"": ""test@test.com""},{""name"": ""Person 2"",""email"": ""example@example.com""}]}"; 

提前致谢

下面给出的答案对于我提出的问题是完美的,但现在我已经领先一步了。 任何人都可以告诉我,如果json中有一个数组,我需要做什么,例如添加一个地址?

 { "data": [ { "name": "Person 1", "email": "test@test.com", "address": { "address1": "my address 1", "address2": "my address 2" } }, { "name": "Person 2", "email": "example@example.com", "address": { "address1": "my address 1", "address2": "my address 2" } } ] } 

这样的事情在过去对我有用:

 JObject o = JObject.Parse(json); // This would be the string you defined above // The next line should yield a List<> of Person objects... List list = JsonConvert.DeserializeObject>(o["data"].ToString()); 

您可能希望按如下方式装饰Person对象:

 [JsonObject(MemberSerialization.OptIn)] public class Person { [JsonProperty] public string name{get;set;} [JsonProperty] public string email{get;set;} } 

您可以使用匿名类型。

 var template = new { data = new Person[] { } }; Person[] emps = JsonConvert .DeserializeAnonymousType(json, template) .data; 

反序列化为:

上述就是C#学习教程:使用Json.net将JSON数组中的多个项添加到C#中的对象分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 public class JsonData { public List Data {get;set;} } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/959600.html

(0)
上一篇 2021年11月23日
下一篇 2021年11月23日

精彩推荐