taContractJsonSerializer反序列化动态键名

taContractJsonSerializer反序列化动态键名

本文介绍了我如何使用DataContractJsonSerializer反序列化动态键名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Web服务,客户端程序可以将密钥发布到其Web方法之一,该方法将返回{"key-client-post","value-from-server-side"},结构返回字符串的行是固定的,但是键名是动态的,它取决于客户端程序.

我的问题是如何使用DataContractJsonSerializer将返回字符串反序列化为.NET对象.

I have a web service, the client program can post a key to one of its web method, and the method will return {"key-client-post", "value-from-server-side"}, the structure of return string is fixed, but the key name is dynamic, it depends on the client program.

My question is how I can deserialize the return string to .NET object using DataContractJsonSerializer.

Thanks.

推荐答案



[DataContract]
public class MyClass
{
    [DataMember]
    public string key;

    [DataMember]
    public string value;
}



包括使用System.Runtime.Serialization;

机制:
如果原始字符串的格式为:{"key-client-post","value-from-server-side"},请将字符串转换为以下格式:{"key":"key-client-post","value :服务器端值"}

然后使用DataContractJsonSerializer反序列化新字符串.



Include using System.Runtime.Serialization;

Mechanism:
If the original string is in format : {"key-client-post", "value-from-server-side"}, Convert the string to the format : {"key" : "key-client-post", "value" : "value-from-server-side"}

Then use the DataContractJsonSerializer to deserialize the new string.

static void Main(string[] args)
{
    String s_key = @"""key"":";
    String s_value = @"""value"":";

    String text = @"{""key1"", ""value1""}"; //The String to be deserialized
    String text_new = text.Insert(text.IndexOf('{')+1, s_key);
    text_new = text_new.Insert(text_new.IndexOf(',') + 1, s_value);
    Console.WriteLine(text_new);

    MemoryStream stream1 = new MemoryStream(ASCIIEncoding.Default.GetBytes(text_new));
    DataContractJsonSerializer deser = new DataContractJsonSerializer(typeof(MyClass));
    MyClass keyValue = (MyClass)deser.ReadObject(stream1);

    //Print deserialized values
    Console.WriteLine(keyValue.key);
    Console.WriteLine(keyValue.value);
}


这篇关于我如何使用DataContractJsonSerializer反序列化动态键名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 10:11