2

Using the Newtonsoft.Json library, imagine I have got

public class Test
{
   public Object Obj { get; set; }
}

Now, attempting to serialize this like so

var json = JsonConvert.SerializeObject(new Test(){ Obj = new Uri(@"http://www.google.com") });

...will give me the following JSON

{
    "Obj": "http://www.google.com"
}

Which is clearly not enough information to deserialize this back into a Uri object, and in fact, attempting to deserialize it will give me a String object instead.

Is there any existing way to correctly serialize and deserialize the type information here so that the object will be read back in as a Uri instead of a String? In this particular case, I am only attempting to interop with a .NET application and it is extremely important that the exact types are deserialized.

Thanks in advance.

4

2 回答 2

2

如果要将字符串转换回 Uri,可以使用自定义转换器属性

转换器

public class UriConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return true;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.String)
        {
            //try to create uri out of the string
            Uri uri;
            if(Uri.TryCreate(reader.Value.ToString(), UriKind.Absolute, out uri))
            {
                return uri;
            }
            //just a string -> return string value
            return reader.Value;
        }

        if (reader.TokenType == JsonToken.Null)
        {
            return null;
        }

        throw new InvalidOperationException("Unable to process JSON");
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        if (null == value)
        {
            writer.WriteNull();
            return;
        }

        if (value is Uri)
        {
            writer.WriteValue(((Uri)value).OriginalString);
            return;
        }

        throw new InvalidOperationException("Unable to process JSON");
    }
}

以及使用属性

 [JsonConverter(typeof(UriConverter))]
 public object Obj {get;set;}

然后,您应该能够确定底层对象是否像 Uri

  var data = JsonConvert.DeserializeObject<YourObject>(yourJSONString);
  if (data.Obj is Uri)
  {
       ... add logic here
  }
  else
  {
       ... not Uri different logic
  }

您还可以查看这篇文章以获取更多信息Json.NET Uri(反)序列化错误

于 2012-06-05T18:51:09.700 回答
1

JSON 只知道 JavaScript 数据类型:字符串、数字和布尔值。URL 不在列表中。

事实上,JSON 的全部要点是允许松散类型的传输。如果您想要强类型传输,请查看更强大的传输协议,例如 WCF 二进制序列化。

于 2012-06-05T18:46:22.763 回答