JSON.Net - 如何反序列化JSON对象,但治疗属性作为字符串而不是JSON? [英] JSON.Net - How to deserialize JSON to object but treating a property as a string instead of JSON?
问题描述
我有一些JSON我想反序列化,但我想对待属性为一个字符串,不是对象之一。
I have some JSON I would like to deserialize, but I want to treat one of the properties as a string, not an object.
作为一个例子,JSON看起来是这样的:
As an example the JSON looks like this:
{
"name":"Frank",
"sex":"male",
"address": {
"street":"nowhere st",
"foo":"bar"
}
}
和我想将它反序列化到这个对象 - 治疗的地址对象作为字符串文字:
And I want to deserialize it to this object - Treating the address object as a string literal:
public class Person
{
public string name;
public string sex;
public string address;
}
我试着从字面上反序列化到这个对象,但得到的错误:
I've tried literally deserializing it to this object but get the error:
无法反序列化JSON对象到类型'System.String'的。
Cannot deserialize JSON object into type 'System.String'.
任何想法?
干杯
推荐答案
最简单的方法是,如果你可以修改您的Person类和喜欢你的地址属性创建一个地址类:
The easiest way is if you can modify your Person class and create an Address class for your Address property like:
public class Person
{
public string name;
public string sex;
public Address address;
}
public class Address
{
public string street;
public string foo;
}
这将让JSON.NET反序列化对象的地址给你。
This will let JSON.NET deserialize the address object for you.
如果您不能修改类 - 该解决方案将需要手动处理人的反序列化,我相信。
If you can't modify your class - the solution will need to be handling deserialization of Person manually, I believe.
这篇关于JSON.Net - 如何反序列化JSON对象,但治疗属性作为字符串而不是JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!