从JsonConvert.SerializeXNode返回具有正确类型的json [英] return json from JsonConvert.SerializeXNode with proper type

查看:747
本文介绍了从JsonConvert.SerializeXNode返回具有正确类型的json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var test = new
            {
                TestStr = "test",
                TestNumber = 123,
                TestDate = new DateTime(1986, 1, 13, 17, 50, 31),
                TestBool = true
            };

var xml = JsonConvert.DeserializeXNode(JsonConvert.SerializeObject(test), "test");

此代码返回漂亮的xml元素:

This code return nice xml element:

<test>
  <TestDate>1986-01-13T14:50:31Z</TestDate>
  <TestBool>true</TestBool>
  <TestNumber>123</TestNumber>
  <TestStr>test</TestStr>
</test>

当我尝试将此xml转换回JSON :

var json = JsonConvert.SerializeXNode(xml, Formatting.None, true);

我只有具有String属性的JSON.

I get JSON only with String properties.

如何获取具有正确类型的json?

What should I do to get json with proper types?

推荐答案

JSON和XML是不同的序列化格式,并且具有不同的功能. JSON可以区分stringnumberboolean,而XML将所有内容都视为字符串.因此,当您从JSON转换为XML并返回时,类型信息会丢失.解决此问题的一种方法是在来回转换时使用强类型的中间模型.换句话说,不是直接从XML转换为JSON,而是将XML反序列化为模型,然后将模型序列化为JSON.该模型将强制数据为正确的类型.

JSON and XML are different serialization formats, and have different capabilities. JSON can differentiate between string, number, and boolean whereas XML treats everything as a string. Therefore, when you convert from JSON to XML and back, the type information gets lost. One way to handle this is to use an strongly-typed intermediate model when converting back and forth. In other words, instead of converting directly from XML to JSON, deserialize your XML to the model, then serialize the model to JSON. The model will force the data to be the correct types.

这是一个例子:

class Program
{
    static void Main(string[] args)
    {
        string xml = @"
        <test>
          <TestDate>1986-01-13T14:50:31Z</TestDate>
          <TestBool>true</TestBool>
          <TestNumber>123</TestNumber>
          <TestStr>test</TestStr>
        </test>";

        XmlSerializer ser = new XmlSerializer(typeof(Test));
        Test test = (Test)ser.Deserialize(new StringReader(xml));
        string json = JsonConvert.SerializeObject(test, Formatting.Indented);
        Console.WriteLine(json);
    }
}

[XmlType("test")]
public class Test
{
    public string TestStr { get; set; }
    public int TestNumber { get; set; }
    public DateTime TestDate { get; set; }
    public bool TestBool { get; set; }
}

输出:

{
  "TestStr": "test",
  "TestNumber": 123,
  "TestDate": "1986-01-13T14:50:31Z",
  "TestBool": true
}

这篇关于从JsonConvert.SerializeXNode返回具有正确类型的json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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