JSON.Net - 如何反序列化JSON对象,但治疗属性作为字符串而不是JSON?字符串、而不是、属性、对象

2023-09-06 18:02:43 作者:梦兮

我有一些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.