4

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

详细说明

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

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; }
}
4

1 回答 1

2

为原始类型编写自定义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;
        }
    }
}

此代码覆盖所有string值的反序列化。如果您仅对特定成员需要此功能,则需要申请JsonConverterAttribute.

于 2013-06-19T11:34:21.630 回答