如何将JObject反序列化到.NET对象?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (184)

很高兴地使用了Newtonsoft JSON库

if (result is Exception)
    var jobjectInstance = JObject.FromObject(result);

现在我知道库可以将JSON文本(即字符串)反序列化为对象

// only works for text (string)
Exception exception = JsonConvert.DeserializeObject<Exception>(jsontext); 

但要找的是:

// now i do already have an JObject instance
Exception exception = jobjectInstance.????
提问于
用户回答回答于

从文件里我发现了这个

JObject o = new JObject(
   new JProperty("Name", "John Smith"),
   new JProperty("BirthDate", new DateTime(1983, 3, 20))
);

JsonSerializer serializer = new JsonSerializer();
Person p = (Person)serializer.Deserialize(new JTokenReader(o), typeof(Person));

Console.WriteLine(p.Name);

类定义:

class Person {
    public string Name { get; internal set; }
    public DateTime BirthDate { get; internal set; }
}
用户回答回答于

可以尝试下这个:

// pick out one album
JObject jalbum = albums[0] as JObject;

// Copy to a static Album instance
Album album = jalbum.ToObject<Album>();

文件:将JSON转换为类型

扫码关注云+社区

领取腾讯云代金券