本文介绍了如何配置Json.NET自定义序列化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于无法控制的原因,我将来自外部服务的数据格式化为字符串数组:[["string_one", "string_two"]]

For reasons beyond my control, I have data coming back from an external service being formatted as an array of array of string: [["string_one", "string_two"]]

我正在尝试将其反序列化为具有两个属性的对象:

I am trying to deserialize this into an object with two properties:

public class MyObject
{
    public string PropertyOne { get; set; }
    public string PropertyTwo { get; set; }
}

我正在使用Json.NET进行所有JSON序列化/反序列化.当我尝试转换字符串数组时,我得到一个异常,说无法将JsonArray转换为MyObject.什么是实现此目的的合适方法?

I'm using Json.NET for all JSON serialization/deserialization. When I attempt to convert the array of array of string, I get an exception saying that JsonArray can't be converted to MyObject. What's the appropriate way to implement this?

推荐答案

最终使用JsonConverter实现了这一点.我将MyObject更改为:

Ended up implementing this using a JsonConverter. I changed MyObject to look like:

[JsonConverter(typeof(MyObjectConverter))]
public class MyObject
{
    public string PropertyOne { get; set; }
    public string PropertyTwo { get; set; }
}

然后实现MyObjectConverter:

And then implemented MyObjectConverter:

public class MyObjectConverter : JsonConverter
{
    public override object ReadJson (JsonReader reader, Type objectType, Object existingValue, JsonSerializer serializer)
    {
        int pos = 0;
        string[] objectIdParts = new string[2];

        while (reader.Read())
        {
            if (pos < 1)
            {
                if (reader.TokenType == JsonToken.String)
                {
                    objectIdParts[pos] = reader.Value.ToString();
                    pos++;
                }
            }
            // read until the end of the JsonReader
        }

        return new MyObject(objectIdParts);
    }

    public override void WriteJson (JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException ();
    }

    public override bool CanWrite {
        get {
            return base.CanWrite;
        }
    }

    public override bool CanRead { get { return true; } }
    public override bool CanConvert (Type objectType)
    {
        return true;
    }
}

这篇关于如何配置Json.NET自定义序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 17:51