简体   繁体   中英

How to deserialize a complex separated (“Column”/“Data”) json to c# object using json.net

I need to parse the following JSON into a List of PackageEntity Object.

Since this json is divided into Column and Data, I am having trouble to do so in an intelligent way.

The JSON looks like:

 { "COLUMNS": ["NSHIPMENTID", "NSHIPPINGCOMPANYID", "NUSERID", "NWEIGHT", "NHEIGHT"], "DATA": [ [7474, null, 12363, "16", "2"], [7593, null, 12363, "64", "7"] ] } 

I would like to deserialize it to a list of the following class:

public class PackageEntity
{
    public int NSHIPMENTID  { get; set; }
    public string NSHIPPINGCOMPANYID  { get; set; }
    public int NUSERID  { get; set; }
    public decimal NWEIGHT  { get; set; }
    public decimal NHEIGHT { get; set; }
} 

what i did so far:

JObject JsonDe = JObject.Parse(responseString);
                int length = JsonDe.Property("DATA").Value.ToArray().Count();

                List<PackageEntity> _list = new List<PackageEntity>();

                for (int i = 0; i < length; i++)
                {
                    PackageEntity pD = new PackageEntity();
                    pD.NSHIPMENTID = JsonDe.Property("DATA").Value.ToArray()[i][0].ToString();
                    pD.NSHIPPINGCOMPANYID = JsonDe.Property("DATA").Value.ToArray()[i][1].ToString();
                    pD.NUSERID = JsonDe.Property("DATA").Value.ToArray()[i][2].ToString();
                    pD.NWEIGHT = JsonDe.Property("DATA").Value.ToArray()[i][3].ToString();
                    pD.NHEIGHT = JsonDe.Property("DATA").Value.ToArray()[i][4].ToString();
                    _list.Add(pD);
                }

You can use the following generic custom JsonConverter to deserialize your data:

public class ColumnarDataToListConverter<T> : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(List<T>);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null)
            return null;
        var list = existingValue as List<T> ?? new List<T>();
        var obj = JObject.Load(reader);
        var columns = obj["COLUMNS"] as JArray;
        var data = obj["DATA"] as JArray;
        if (data == null)
            return list;
        list.AddRange(data
            .Select(item => new JObject(columns.Zip(item, (c, v) => new JProperty((string)c, v))))
            .Select(o => o.ToObject<T>(serializer)));
        return list;
    }

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

Then use it as follows:

var settings = new JsonSerializerSettings { Converters = new[] { new ColumnarDataToListConverter<PackageEntity>() } };
var list = JsonConvert.DeserializeObject<List<PackageEntity>>(responseString, settings);

Note the use of Enumerable.Zip() to pair up the entries in the column array with the entries in each row of the data array into a temporary JObject for deserialization.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM