简体   繁体   中英

Get key value pair from JSON string

I have a json string like

{
  [
    "EnrityList": "Attribute",
    "KeyName": "AkeyName",
    "Value": "Avalue"
  ],
  [
    "EnrityList": "BusinessKey",
    "KeyName": "AkeyName",
    "Value": "Avalue"
  ]
}

I have serialized and got an object array. Could anyone help me to get the key value pair from these object array.

You can use JsonConvert from Newtonsoft.Json to deserialize json into Dictionary.

Dictionary<string, object> values = 
    JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonstring);

First convert the above string in proper json format by using :

str=str.Replace('[', '{');
str=str.Replace(']', '}');
//replace first occurance of {
int startPos = str.IndexOf('{');
str=str.Substring(0,startPos)+" ["+str.Substring(startPos + 1);
//replace last occurance of }
int endPos = str.LastIndexOf('}');
str=str.Substring(0,endPos)+"]";

This makes the string

str = [{"EnrityList":"Attribute","KeyName":"AkeyName","Value":"Avalue"}, {"EnrityList":"BusinessKey","KeyName":"AkeyName","Value":"Avalue"} ]   

Now, since you got the json string, you can easily work with it.
we can use method as given by

How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?

foreach(KeyValuePair<string, string> entry in myDictionary)
{
    // do something with entry.Value or entry.Key
}

Looking at your example, You are trying to receive a List of certain type of elements, So First, You will need a class to represent your data type.

class MyType
{    
  string  EnrityList;
  string  KeyName;
  string  Value;    
}

Then use DesrializeObject method to store it in the variable

var values = JsonConvert.DeserializeObject<List<MyType>>(jsonstring);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM