Click here to Skip to main content
15,890,282 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.
Posted
Comments
__Untitled 23-May-12 21:23pm    
So it is impossible to solve such a case using DataContractJsonSerializer, right?

Normally, deserialization based on Data Contract should go in a pair with serialization. Data Contract serializers have certain format, not all data can fit it. You define data classes and add attributes to it, and this defines format meta-data. In some cases, you can design the set of data classes to match some available data format.

Please see:
http://msdn.microsoft.com/en-us/library/ms733127.aspx[^].

—SA
 
Share this answer
 
Please refer similar discussion:
Deserialize JSON into C# dynamic object[^]
 
Share this answer
 
Create a class which will hold the data from the string.

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

    [DataMember]
    public string value;
}


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.
C#
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);
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900