Is this possible in JSON?

自作多情 提交于 2019-12-10 13:54:05

问题


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


回答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.



来源:https://stackoverflow.com/questions/9209272/is-this-possible-in-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!