Json.net如何将对象序列化为值 [英] Json.net how to serialize object as value

查看:58
本文介绍了Json.net如何将对象序列化为值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经仔细研究了文档,StackOverflow等,似乎找不到这个...

I've pored through the docs, StackOverflow, etc., can't seem to find this...

我想要做的是将对象的简单值类型序列化/反序列化为值,而不是对象,就像这样:

What I want to do is serialize/deserialize a simple value-type of object as a value, not an object, as so:

public class IPAddress
{
    byte[] bytes;

    public override string ToString() {... etc.
}

public class SomeOuterObject
{
    string stringValue;
    IPAddress ipValue;
}

IPAddress ip = new IPAddress("192.168.1.2");
var obj = new SomeOuterObject() {stringValue = "Some String", ipValue = ip};
string json = JsonConverter.SerializeObject(obj);

我想要的是让json像这样序列化:

What I want is for the json to serialize like this:

// json = {"someString":"Some String","ipValue":"192.168.1.2"} <- value serialized as value, not subobject

不是ip成为嵌套对象的地方,例如:

Not where the ip becomes a nested object, ex:

// json = {"someString":"Some String","ipValue":{"value":"192.168.1.2"}}

有人知道该怎么做吗?谢谢! (P.S.我将Json序列化固定在大型的老式.NET代码库上,因此我无法真正更改任何现有类型,但可以对它们进行扩充/分解/修饰以促进Json序列化.)

Does anyone know how to do this? Thanks! (P.S. I am bolting Json serialization on a large hairy legacy .NET codebase, so I can't really change any existing types, but I can augment/factor/decorate them to facilitate Json serialization.)

推荐答案

您可以使用针对IPAddress类的自定义JsonConverter处理此问题.这是您需要的代码:

You can handle this using a custom JsonConverter for the IPAddress class. Here is the code you would need:

public class IPAddressConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(IPAddress));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return new IPAddress(JToken.Load(reader).ToString());
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        JToken.FromObject(value.ToString()).WriteTo(writer);
    }
}

然后,在IPAddress类中添加一个[JsonConverter]属性,您就可以开始了:

Then, add a [JsonConverter] attribute to your IPAddress class and you're ready to go:

[JsonConverter(typeof(IPAddressConverter))]
public class IPAddress
{
    byte[] bytes;

    public IPAddress(string address)
    {
        bytes = address.Split('.').Select(s => byte.Parse(s)).ToArray();
    }

    public override string ToString() 
    { 
        return string.Join(".", bytes.Select(b => b.ToString()).ToArray()); 
    }
}

这是一个工作示例:

class Program
{
    static void Main(string[] args)
    {
        IPAddress ip = new IPAddress("192.168.1.2");
        var obj = new SomeOuterObject() { stringValue = "Some String", ipValue = ip };
        string json = JsonConvert.SerializeObject(obj);
        Console.WriteLine(json);
    }
}

public class SomeOuterObject
{
    public string stringValue { get; set; }
    public IPAddress ipValue { get; set; }
}

输出:

{"stringValue":"Some String","ipValue":"192.168.1.2"}

这篇关于Json.net如何将对象序列化为值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆