c# – 如何反序列化JSON数据,有时候这是一个空数组,有时候是一个字符串值

我从服务器获取
JSON数据,但是我发现,当字符串值为空时,服务器返回一个空数组.不是空白字符串(“”).所以我混淆了如何处理这种情况,我使用JSON.NET来反序列化JSON数据,我应该覆盖JsonConverter中的ReadJson方法吗?谢谢大家提前!

详细说明

由于在WeiboPOI类中,我将Poiid和Address定义为字符串,当服务器返回字符串数据时,我的程序可以正常反序列化JSON数据,但是当Poiid或Address为空时,服务器返回一个空数组,而不是空字符串( “”),所以我的程序无法对JSON数据进行deserilize.

JSON数据

{
  "pois": [
    {
      "pid": "P01QN07N6S5",
      "longitude": "109.53466",
      "latitude": "26.96971",
      "name": "TEST1",
      "city_name": "TEST1",
      "province_name": "TEST1",
      "address": [

      ],
      "telephone": "",
      "category": "190108",
      "navigator": "",
      "pic_url": ""
    },
    {
      "pid": [

      ],
      "longitude": "113.32608",
      "latitude": "23.15884",
      "name": "TEST2",
      "city_name": "TEST2",
      "province_name": "TEST2",
      "address": "Test address",
      "telephone": "020-61089463",
      "category": "60000",
      "navigator": "",
      "pic_url": ""
    }
  ],
  "total_number": "68467"
}

图片

DTO

public class WeiboPOI : IWeiboModel
{
[DataMember]
public string Poiid { get; set; }

[DataMember]
public string Title { get; set; }

// This is a string value not array.
// So the server returns an empty array will have an exception.
[DataMember]
public string Address { get; set; }

[JsonProperty("lon")]
public string Longitude { get; set; }

[JsonProperty("Lat")]
public string Latitude { get; set; }

[DataMember]
public string Category { get; set; }

[DataMember]
public string City { get; set; }

[DataMember]
public string Province { get; set; }

[DataMember]
public string Country { get; set; }

[DataMember]
public string Url { get; set; }

[DataMember]
public string Phone { get; set; }

[DataMember]
public string Postcode { get; set; }

[DataMember]
public string WeiboId { get; set; }

[DataMember]
public string Icon { get; set; }

[DataMember]
public string Extra { get; set; }

[DataMember]
public string Rid { get; set; }

[DataMember]
public string Categorys { get; set; }

[DataMember]
public string CategoryName { get; set; }

[DataMember]
public string CheckinUserNum { get; set; }

[DataMember]
public string PoiPic { get; set; }

[DataMember]
public int Pintu { get; set; }

[DataMember]
public string PoiStreetAddress { get; set; }

[DataMember]
public string PoiStreetSummary { get; set; }

[DataMember]
public int Enterprise { get; set; }

[DataMember]
public string CheckinTime { get; set; }

public string RawSource { get; set; }
}

最佳答案 为基本类型编写自定义JsonConverter非常简单:

using System;
using Newtonsoft.Json;

namespace So17171737_ArrayOrString
{
    class StringOrArrayConverter : JsonConverter
    {
        public override object ReadJson (JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            switch (reader.TokenType) {
                case JsonToken.String:
                case JsonToken.Null:
                    return reader.Value;
                case JsonToken.StartArray:
                    reader.Read();
                    if (reader.TokenType != JsonToken.EndArray)
                        throw new JsonReaderException("Empty array expected.");
                    return "";
            }
            throw new JsonReaderException("Expected string or null or empty array.");
        }

        public override void WriteJson (JsonWriter writer, object value, JsonSerializer serializer)
        {
            serializer.Serialize(writer, value);
        }

        public override bool CanConvert (Type objectType)
        {
            return objectType == typeof(string);
        }
    }

    class Program
    {
        private const string json = @"
{
    s1: 'str1',
    s2: [],
    s3: null
}
";

        static void Main ()
        {
            Foo foo = JsonConvert.DeserializeObject<Foo>(json, new JsonSerializerSettings {
                Converters = { new StringOrArrayConverter() }
            });
            Console.WriteLine(JsonConvert.SerializeObject(foo, Formatting.Indented));
            Console.ReadKey();
        }

        class Foo
        {
            public string s1, s2, s3;
        }
    }
}

此代码将覆盖所有字符串值的反序列化.如果只需要特定成员,则需要应用JsonConverterAttribute.

点赞