JSON.Net结构体序列差异 [英] JSON.Net Struct Serialization Discrepancy

查看:154
本文介绍了JSON.Net结构体序列差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用JSON.Net序列化/反序列化结构,一个内置的结构类型(如System.Drawing.Size)序列化为一个字符串,而自定义的结构类型序列化为一个JSON对象。

When using JSON.Net to serialize/deserialize structs, a build-in struct type (like System.Drawing.Size) serializes to a string, whereas a custom struct type serializes to a JSON object.

例如:

using System;
using System.Drawing;
using Newtonsoft.Json;

namespace TestJsonNet
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(JsonConvert.SerializeObject(new Size(50, 50)));
            Console.WriteLine(JsonConvert.SerializeObject(new Size2(50, 50)));
        }
    }

    struct Size2
    {
        public int Width { get; set; }
        public int Height { get; set; }
        public Size2(int w, int h) : this()
        {
            Width = w; Height = h;
        }
    }
}



输出以下内容:

Outputs the following:

"50, 50"
{"Width":50,"Height":50}

我能理解其背后序列化结构为一个字符串的思维,因为内存布局始终是相同的;然而,为什么序列化的自定义结构时的差异?

I can understand the thinking behind serializing a struct to a string, since the memory layout is always the same; however, why the discrepancy when serializing a custom struct?

另外,我想(内部遗留原因),喜欢有JSON.Net序列像后一种情况下结构(即作为JSON,而不是字符串)。如果有可能,这怎么可能实现呢?

Also, I would (for internal legacy reasons), like to have JSON.Net serialize structs like the latter case (i.e. as JSON, not string). If it's possible, how can that be achieved?

推荐答案

使用反射,你可以解决这个问题。
我把解决方案的一部分,你认为自己和使用反射来获取属性的名称和值。

Using reflection you could solve this problem. I took part of the solution you suggested yourself and used reflection to get the property names and values.

class StructConverter : JsonConverter
{
    public override void WriteJson(
        JsonWriter writer, object value, JsonSerializer serializer)
    {
        var myObject = (object)value;
        var jObject = new JObject();

        Type myType = myObject.GetType();
        IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());

        foreach (PropertyInfo prop in props)
        {

            jObject.Add(prop.Name, prop.GetValue(myObject, null).ToString());
        }
        serializer.Serialize(
            writer,  jObject);
    }



...

....

    public override bool CanConvert(Type objectType)
    {
        return objectType.IsValueType;
    }
}

这篇关于JSON.Net结构体序列差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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