我怎样才能用连载一DataContractJsonSerializer字符串数组,JSON? [英] How can I serialise a string array to JSON using DataContractJsonSerializer?

查看:127
本文介绍了我怎样才能用连载一DataContractJsonSerializer字符串数组,JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎是同样的问题,下面,但这个问题的答案并没有解决它:

This seems to be the same question as below but that answer hasn't resolved it:

<一个href=\"http://stackoverflow.com/questions/8204320/deserializing-a-simple-json-array-with-datacontractjsonserializer\">Deserializing一个简单的JSON阵列

我使用DataContractJsonSerializer转换从XML到JSON,反之亦然。一切工作与复杂的数据类型和复杂数据类型的数组,但我在制作的JSON字符串数组的一个问题。

I am using DataContractJsonSerializer to convert from XML to JSON and vice versa. Everything works with complex data types and arrays of complex data types but I'm having a problem producing JSON for a string array.

我需要产生的JSON应该有这样的结构:

The JSON I need to produce should have this structure:

{
  "data": {
    "x_axis": {
      "labels": [ "Jan", "Feb", "Mar", "Apr","May", "Jun", "Jul", Aug","Sep", Oct", "Nov", "Dec" ]
     }
  }
}

我使用的对象包括: -

The objects I am using are:-

LineChartData:

LineChartData:

[DataContract]
public class LineChartData
{
    [DataMember(Name = "x_axis")]
    public LineChartXAxis XAxis { get; set; }
}

LineChartXAxis:

LineChartXAxis:

[DataContract]
public class LineChartXAxis
{
    [DataMember(Name = "labels")]
    public string[] Labels { get; set; }
}

我想转换看起来像这样的XML:

The XML I am trying to convert looks like this:

<LineChartData>
  <XAxis>
    <Labels>Jan</Labels>
    <Labels>Feb</Labels>
    <Labels>Mar</Labels>
    <Labels>Apr</Labels>
    <Labels>May</Labels>
    <Labels>Jun</Labels>
    <Labels>Jul</Labels>
    <Labels>Aug</Labels>
    <Labels>Sep</Labels>
    <Labels>Oct</Labels>
    <Labels>Nov</Labels>
    <Labels>Dec</Labels>
  </XAxis>
</LineChartData>

我deserialising code是:

My deserialising code is:

var serialiser = new XmlSerializer(typeof(LineChartData));
var stringReader = new StringReader(xml);

var result = serialiser.Deserialize(stringReader);

我回来后总是JSON有一个空的标签数组:

The JSON I get back always has an empty labels array:

{
  "data": {
    "x_axis": {
      "labels":[]
    }
  }
}

应该如何定义标签属性LineChartXAxis正确的连载JSON?

How should I be defining the Labels property in LineChartXAxis to serialise the JSON correctly?

推荐答案

您有几个问题在这里:


  1. &LT;标签及GT; 集合不具有外容器元素。默认情况下的XmlSerializer 序列集合时增加了一个容器元素。要跳过外包装元素中,添加一个 [的XmlElement(标签)] 属性添加到标签属性。 ( XML序列化属性和<一个HREF =htt​​ps://msdn.microsoft.com/en-us/library/ms733811%28v=vs.110%29.aspx相对=nofollow>数据契约属性是相互独立的,既可能无一影响其他组被应用。)

  1. Your <Labels> collection does not have an outer container element. By default XmlSerializer adds a container element when serializing a collection. To skip the outer wrapper element, add an [XmlElement("Labels")] attribute to the Labels property. (XML serializer attributes and data contract attributes are mutually independent and may both be applied without one set affecting the other.)

即。您的实际问题是读你的XML则没有写入JSON字符串列表。

I.e. your actual problem is in reading your list of strings from XML not writing then to JSON.

您JSON具有对应于外根元素{数据:{...}} 对象。您需要序列化时考虑到这一点。 (也许你做的,这是不显示。)

Your JSON has an outer root element corresponding to the {"data": {...}} object. You need to account for this when serializing. (Maybe you do and this is not shown.)

因此​​,下面应该工作:

Thus the following should work:

[DataContract]
public class LineChartData
{
    [DataMember(Name = "x_axis")]
    public LineChartXAxis XAxis { get; set; }
}

[DataContract]
public class LineChartXAxis
{
    [DataMember(Name = "labels")]
    [XmlElement("Labels")]
    public string[] Labels { get; set; }
}

[DataContract]
public class RootObject<T>
{
    [DataMember(Name = "data")]
    public T Data { get; set; }
}

public static class RootObjectExtensions
{
    public static RootObject<T> FromData<T>(T data)
    {
        return new RootObject<T> { Data = data };
    }
}

然后用它们像

        var data = xmlString.LoadFromXML<LineChartData>();
        var jsonString = DataContractJsonSerializerHelper.GetJson(RootObjectExtensions.FromData(data));

通过扩展方法:

public static class XmlSerializerHelper
{
    public static T LoadFromXML<T>(this string xmlString, XmlSerializer serial = null)
    {
        using (StringReader reader = new StringReader(xmlString))
        {
            object result = (serial ?? new XmlSerializer(typeof(T))).Deserialize(reader);
            if (result is T)
                return (T)result;
        }
        return default(T);
    }
}

public static class DataContractJsonSerializerHelper
{
    public static string GetJson<T>(T obj, DataContractJsonSerializer serializer = null)
    {
        using (var memory = new MemoryStream())
        {
            (serializer ?? new DataContractJsonSerializer(typeof(T))).WriteObject(memory, obj);
            memory.Seek(0, SeekOrigin.Begin);
            using (var reader = new StreamReader(memory))
            {
                return reader.ReadToEnd();
            }
        }
    }
}

顺便说一下,作为替代,你可以看看 Json.NET ,该有能力< A HREF =htt​​p://www.newtonsoft.com/json/help/html/ConvertingJSONandXML.htm相对=nofollow>直接转换成JSON和XML之间

这篇关于我怎样才能用连载一DataContractJsonSerializer字符串数组,JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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