I am currently working with json.net ! I know how to deserialize json data and how to map with our class. Now I am eager about some queries !
Suppose my jsonstrings is
"attributes":{
"color":"Brown",
"condition":"Used",
"currency":"USD",
"price":"10500",
"price_display":"$10,500",
}
and my attribute class ( in which i want to deserialize above string) is
Public class Attribute
{
public string name{ get; set; }
public string value{ get; set; }
}
Now I am using following code for deserialization.!
JavaScriptSerializer ser = new JavaScriptSerializer();
<classname> p = ser.Deserialize<classname>(jsonString);
And Obviously this code is not going to work for above jsonstring at all.
Now How can I bind these name value pair in one class ?? Is this possible ?
In future, attributes may b more than 10 but format will be same as name value pair
EDIT: I’m sorry, but somehow I interpreted your question as if you wanted to serialize, and not deserialize (but I’ll keep the original below anyway, as I think it’s good knowledge :)).
Try to deserialize your JSON string to
Dictionary<string,string>instead of yourAttribute. I have a hunch it might work. Then, you can adjust the rest of your code to use that dictionary or you can convert to collection of yourAttributeinstances.The original answer (related to serializing, which was the opposite of what you asked for) below.
I don’t think so, but if the intention is to use it on the client this way:
… then what you’re after is called “associative array”, as it’s equivalent to this:
… as it’s not really an array, but it’s an object (javascript provides these two ways to reference object properties; e.g.
window.onloadis the same aswindow["onload"])…… and you can achieve this with the JavaScriptSerializer if you serialize
Dictionary<string,string>to JSON string (in other words, change yourAttributeclass toKeyValuePair<string,string>, or otherwise create such dictionary differently.