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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4441466/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 15:02:00  来源:igfitidea点击:

How to deserialize a JObject to .NET object

.netjsonexceptionserializationjson.net

提问by Sebastian

I happily use the Newtonsoft JSON library. For example, I would create a JObjectfrom a .NET object, in this case an instance of Exception (might or might not be a subclass)

我很高兴使用Newtonsoft JSON 库。例如,我会JObject从 .NET 对象创建一个,在这种情况下是一个 Exception 实例(可能是也可能不是子类)

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

now I know the library can deserialize JSON text (i.e. a string) to an object

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

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

but what I am looking for is:

但我正在寻找的是:

// now i do already have an JObject instance
Exception exception = jobjectInstance.????

Well it is clear that I can go from on JObjectback to JSON text and then use the deserialize functionality, but that seems backwards to me.

很明显,我可以从头JObject回到 JSON 文本,然后使用反序列化功能,但这对我来说似乎是倒退。

回答by Tien Do

According to this post, it's much better now:

根据这篇文章,现在好多了:

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

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

Documentation: Convert JSON to a Type

文档:将 JSON 转换为类型

回答by Sebastian

From the documentation I found this

从文档中我发现了这个

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);

The class definition for Personshould be compatible to the following:

的类定义Person应与以下内容兼容:

class Person {
    public string Name { get; internal set; }
    public DateTime BirthDate { get; internal set; }
}

Edit

编辑

If you are using a recent version of JSON.net anddon't need custom serialization, please see TienDo's answer above (or below if you upvote me :P ), which is more concise.

如果您使用的是最新版本的 JSON.net并且不需要自定义序列化,请参阅上面的 TienDo 的答案(如果您投票给我 :P,请参阅下面的答案),它更简洁。

回答by Ivan Lopez

Too late, just in case some one is looking for another way:

太晚了,以防万一有人正在寻找另一种方式:

void Main()
{
    string jsonString = @"{
  'Stores': [
    'Lambton Quay',
    'Willis Street'
  ],
  'Manufacturers': [
    {
      'Name': 'Acme Co',
      'Products': [
        {
          'Name': 'Anvil',
          'Price': 50
        }
      ]
    },
    {
      'Name': 'Contoso',
      'Products': [
        {
          'Name': 'Elbow Grease',
          'Price': 99.95
        },
        {
          'Name': 'Headlight Fluid',
          'Price': 4
        }
      ]
    }
  ]
}";

    Product product = new Product();
    //Serializing to Object
    Product obj = JObject.Parse(jsonString).SelectToken("$.Manufacturers[?(@.Name == 'Acme Co' && @.Name != 'Contoso')]").ToObject<Product>();

    Console.WriteLine(obj);
}


public class Product
{
    public string Name { get; set; }
    public decimal Price { get; set; }
}