JSON.Net - How to deserialize JSON to object but treating a property as a string instead of JSON?

人走茶凉 提交于 2019-12-12 12:20:58

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!