反序列化与已知和未知领域JSON [英] Deserialize json with known and unknown fields

查看:139
本文介绍了反序列化与已知和未知领域JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于以下JSON结果:
默认的JSON结果是一组已知的领域:

Given following json result: The default json result has a known set of fields:

{
    "id": "7908",
    "name": "product name"
}

但可以用其他字段进行扩展(在这个例子中 _unknown_field_name_1 _unknown_field_name_2 ),它的名字都没有请求的结果时称。

But can be extended with additional fields (in this example _unknown_field_name_1 and _unknown_field_name_2) of which the names are not known when requesting the result.

{
    "id": "7908",
    "name": "product name",
    "_unknown_field_name_1": "some value",
    "_unknown_field_name_2": "some value"
}

我想JSON结果被序列化和反序列化,并从一类为已知油田属性和映射未知的字段(其中有没有属性)一个属性(或多个属性)像一本字典等等他们可以访问和修改。

I would like the json result to be serialized and deserialized to and from a class with properties for the known fields and map the unknown fields (for which there are no properties) to a property (or multiple properties) like a dictionary so they can be accessed and modified.

public class Product
{
    public string id { get; set; }
    public string name { get; set; }
    public Dictionary<string, string> fields { get; set; }
}

我想我需要一种方法来插入JSON序列化和失踪人员本人(无论是序列化和反序列化)进行映射。
我一直在寻找各种可能性:

I think I need a way to plug into a json serializer and do the mapping for the missing members myself (both for serialize and deserialize). I have been looking at various possibilities:


  • json.net和定制合同解析器(无法弄清楚如何做到这一点)

  • datacontract串行器(只能覆盖onserialized,onserializing)

  • 序列化到动态并进行自定义映射(这可能工作,但似乎很多工作)

  • 让产品从DynamicObject(串行器与反思工作,不调用trygetmember和trysetmember方法)
  • 继承

我使用restsharp,但任何串行器可以插入。

I'm using restsharp, but any serializer can be plugged in.

哦,我不能改变JSON结果和或<一个href=\"http://stackoverflow.com/questions/13072447/how-to-deserialize-variable-size-json-string-with-variable-names\">this没有帮助我满意。

Oh, and I cannot change the json result, and this or this didn't help me either.

更新:
这看起来更像是:<一href=\"http://geekswithblogs.net/DavidHoerster/archive/2011/07/26/json.net-custom-convertersndasha-quick-tour.aspx\">http://geekswithblogs.net/DavidHoerster/archive/2011/07/26/json.net-custom-convertersndasha-quick-tour.aspx

推荐答案

请参见的https://gist.github .COM / LodewijkSioen / 5101814

什么你要找的是一个自定义的 JsonConverter

What you were looking for was a custom JsonConverter

这篇关于反序列化与已知和未知领域JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆