6

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

Chintan
  • 2,768
  • 4
  • 27
  • 43

1 Answers1

1

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 your Attribute. 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 your Attribute instances.


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:

attributes["color"] // returns Brown
attributes["price"] // returns 10500

... then what you're after is called "associative array", as it's equivalent to this:

attributes.color
attributes.price

... as it's not really an array, but it's an object (javascript provides these two ways to reference object properties; e.g. window.onload is the same as window["onload"])...

... and you can achieve this with the JavaScriptSerializer if you serialize Dictionary<string,string> to JSON string (in other words, change your Attribute class to KeyValuePair<string,string>, or otherwise create such dictionary differently.