简体   繁体   English

使用DataContractJsonSerializer设置JSON对象root

[英]Set JSON object root using DataContractJsonSerializer

When serializing an object using the System.Runtime.Serialization.Json.DataContractJsonSerializer , is there a way to set the "root" or top-level key in the JSON string? 使用System.Runtime.Serialization.Json.DataContractJsonSerializer序列化对象时,有没有办法在JSON字符串中设置“root”或顶级键?

For example, here is a class: 例如,这是一个类:

[DataContract]
public class Person
{
    public Person() { }
    public Person(string firstname, string lastname)
    {
        this.FirstName = firstname;
        this.LastName = lastname;
    }

    [DataMember]
    public string FirstName { get; set; }

    [DataMember]
    public string LastName { get; set; }
}

When it is serialized using... 当它使用...序列化时

public static string Serialize<T>(T obj)
{
    Json.DataContractJsonSerializer serializer = 
        new DataContractJsonSerializer(obj.GetType());
    MemoryStream ms = new MemoryStream();
    serializer.WriteObject(ms, obj);
    string retVal = Encoding.Default.GetString(ms.ToArray());
    ms.Dispose();
    return retVal;
}

The produced JSON string looks like: 生成的JSON字符串如下所示:

{"FirstName":"Jane","LastName":"McDoe"}

Is there a way to have the serializer prepend some value? 有没有办法让序列化器前置一些值?

For example: 例如:

{Person: {"FirstName":"Jane","LastName":"McDoe"}}

Of course I could simply change my Serialize method to wrap the returned JSON string, eg: 当然我可以简单地更改我的Serialize方法来包装返回的JSON字符串,例如:

string retVal = "{Person:" + Encoding.Default.GetString(ms.ToArray()) + "}";

But I was wondering if there was some way to tell the serializer to add it? 但我想知道是否有某种方法告诉序列化程序添加它? The namespace property on the DataContract attribute didn't seem to help. DataContract属性上的namespace属性似乎没有帮助。

You can do that, but it's not something too pretty - you need to know some of the JSON to XML mapping rules which the DataContractJsonSerializer uses. 你可以这样做,但它不是太漂亮 - 你需要知道DataContractJsonSerializer使用的一些JSON到XML映射规则。 For the simple case, where you just want to wrap the object in the type name, it's fairly simple - the code below does that. 对于简单的情况,你只想将对象包装在类型名称中,这很简单 - 下面的代码就是这样做的。 You need to create the serializer with the "root" name you want (in this case I used the type name), and pass to it a XmlDictionaryWriter instance which has been given the root element. 您需要使用所需的“根”名称创建序列化程序(在本例中我使用了类型名称),并向其传递已赋予根元素的XmlDictionaryWriter实例。

public class StackOverflow_7930629
{
    [DataContract]
    public class Person
    {
        public Person() { }
        public Person(string firstname, string lastname)
        {
            this.FirstName = firstname;
            this.LastName = lastname;
        }

        [DataMember]
        public string FirstName { get; set; }

        [DataMember]
        public string LastName { get; set; }
    }

    public static string Serialize<T>(T obj)
    {
        DataContractJsonSerializer serializer =
            new DataContractJsonSerializer(typeof(T), typeof(T).Name);
        MemoryStream ms = new MemoryStream();
        XmlDictionaryWriter w = JsonReaderWriterFactory.CreateJsonWriter(ms);
        w.WriteStartElement("root");
        w.WriteAttributeString("type", "object");
        serializer.WriteObject(w, obj);
        w.WriteEndElement();
        w.Flush();
        string retVal = Encoding.Default.GetString(ms.ToArray());
        ms.Dispose();
        return retVal;
    }
    public static void Test()
    {
        Console.WriteLine(Serialize(new Person("Jane", "McDoe")));
    }
}

As was mentioned in one of the comments, working with JSON and the DataContractJsonSerializer isn't something too friendly. 正如其中一条评论中所提到的,使用JSON和DataContractJsonSerializer并不是太友好了。 Some JSON-specific libraries such as JSON.NET or the JsonValue types (nuget package JsonValue) can make your life a lot easier. 一些JSON特定的库(如JSON.NET或JsonValue类型(nuget包JsonValue))可以让您的生活更轻松。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法使用DataContractJsonSerializer将对象序列化为JSON - Unable to Serialize Object to JSON Using DataContractJsonSerializer 使用DataContractJsonSerializer作为JSON数组序列化对象 - Serialize an object using DataContractJsonSerializer as a json array 使用 DataContractJsonSerializer 将字典序列化为 JSON 对象 - Serialize a Dictionary as JSON object using DataContractJsonSerializer 在C#中使用DataContractJsonSerializer反序列化JSON对象 - Deserialization of JSON object by using DataContractJsonSerializer in C# 使用DataContractJsonSerializer对JSON对象进行部分反序列化 - Partial deserialization of JSON object by using DataContractJsonSerializer 如何使用DataContractJsonSerializer使用从Web(以JSON形式)获取的数据设置对象属性的子集 - How to set a subset of properties of an object using data obtained from web (in form of JSON) using DataContractJsonSerializer 使用DataContractJsonSerializer读取JSON - Read JSON using DataContractJsonSerializer 在 C# 中使用 DataContractJsonSerializer 使用 List&lt;&gt; 反序列化 JSON 对象 - Deserialization of JSON object with List<> using DataContractJsonSerializer in C# 如何使用JSON.NET或DataContractJsonSerializer反序列化未类型化的对象 - How to deserialize an untyped object using JSON.NET or DataContractJsonSerializer 使用DataContractJsonSerializer将Json反序列化为C#动态对象 - Deserialize Json into a C# dynamic object using DataContractJsonSerializer
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM