问题
I have some JSON I would like to deserialize, but I want to treat one of the properties as a string, not an object.
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:
Cannot deserialize JSON object into type 'System.String'.
Any ideas?
Cheers
回答1:
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;
}
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.
来源:https://stackoverflow.com/questions/9952302/json-net-how-to-deserialize-json-to-object-but-treating-a-property-as-a-string