【问题标题】:JsonConvert convert to custom objectJsonConvert 转换为自定义对象
【发布时间】:2015-05-25 11:42:00
【问题描述】:

我做了一个简单的自定义JsonConvert 类。现在我正在尝试将 JSON 数据转换为自定义类,如下所示:

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
    //JObject jo = JObject.Load(reader);
    MyItem instance = serializer.Deserialize<MyItem>(reader);

    // want to do more thing here...
}

每次执行Deserialize&lt;&gt;() 方法时,它都会重新进入ReadJson 方法,从而使我处于一个永无止境的循环中。

如何将 JSON 数据转换为我的自定义对象,而不会陷入永无止境的循环?


更新

我收到的 JSON 是通用的。我需要自定义转换器将其映射到正确的类型。 JSON 如下所示:

{
    /* Base obj properties, should be mapped to Page.cs */
    "$type": "App.Models.Page, App",
    "title": "Page title",
    "technicalName": "some_key",
    "fields": [

        /* Should be mapped to InputField.cs */
        {
            "$type": "App.Models.InputField, App",
            "type": "input",
            "typeTitle": "Input",
            "title": "Input",
            "technicalName": "input",
            "inputType": "text",
            "defaultValue": "Input default value"
        },

        /* Should be mapped to TextareaField.cs */
        {
            "$type": "App.Models.TextareaField, App",
            "type": "textarea",
            "typeTitle": "Textarea",
            "title": "Textarea",
            "technicalName": "textarea",
            "defaultValue": "default textarea value"
        }
    ]
}

简而言之,我的类文件如下所示:

class Page
{
    public string Title {get;set;}
    public string TechnicalName {get;set;}

    public List<Field> Fields {get;set;} // Note the base class "Field"
}

class InputField : Field // Field has base properties
{
 // InputField has its own properties
}

class TextareaField : Field // Field has base properties
{
 // TextareaField has its own properties
}

类型名称处理

我已经设置了 json 格式化程序设置:

jsonOutputFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.Objects;
jsonInputFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.Auto;

当我通过Web API 输出Page 对象时,我得到一个与上面完全相同的JSON 结构。当我发回准确的 JSON 数据时,我希望它能够很好地映射回 Page 对象,并在 Field 列表属性中具有正确的类型。

但所有Fields 都映射到它的基类Field,而不是$type 中定义的类型。

因此,目前 JSON 格式化程序非常适合输出。它显示了所有$types。但是输入映射并没有真正映射回它的特定类型。

【问题讨论】:

  • 您为什么首先创建自定义JsonConvert?为什么不使用图书馆提供的呢?
  • @YuvalItzchakov 因为我有一个页面发布了一个可以是通用类型的 JSON 数组。我最终将使用自定义转换器将其映射回正确的类型。
  • 您可以尝试将方法签名更改为public new object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  • @JurgenCamilleri 不起作用,这是一个需要重写的抽象方法。
  • @Vivendi 发布您的 JSON 结构。

标签: c# json.net


【解决方案1】:

鉴于您在 Web API 端使用 Json.NET,您不需要自定义 JsonConverter。您可以明确告诉JsonFormatter(内部使用Json.NET)使用TypeNameHandling.All。这样,它就可以准确地知道在给定IEnumerable&lt;BaseType&gt; 的情况下要反序列化哪种类型。更多信息请见how to deserialize JSON into IEnumerable<BaseType> with Newtonsoft JSON.NET

【讨论】:

    【解决方案2】:
    public static class ConvertToJson
    { 
        public static T Deserialize<T>(string json)
        {
            using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
                return (T)serializer.ReadObject(ms);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-07
      • 1970-01-01
      • 2021-11-01
      • 2014-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多