Read JSON from string and get access to keys - c#

Can I read JSON from string and iterate if I don't know what kind of key it stores?
Generally, it will be key value pair?
I know that I can use:
dynamic dynamicJson = JsonConvert.DeserializeObject(json);
But I don't have an access to keys.
I'm not trying to deserialize into strongly-typed .net objects.

You can use JObject.Parse method and iterate through KeyValuePair of JObject:
var jObject = JObject.Parse(json);
foreach (KeyValuePair<string, JToken> kvp in jObject)
{
// Your code.
}

Related

Extracting data from JSON structure in C#

JSON data:
{
"return": {
"output01": "Test request success!!",
"output02": "test request"
}
}
C# code:
JObject obj = JObject.Parse(jsonString);
JToken jToken = obj["return"];
foreach (JToken item in jToken)
{
string output1_param = item["output01"].ToString();
string output2_param = item["output02"].ToString();
}
Think of a repeat case.
System.InvalidOperationException: 'Cannot access child value on
Newtonsoft.Json.Linq.JProperty.'
What's wrong?
item is a JProperty, so it does not support indexer by object key (for example string one). You need either strip foreach:
JToken jToken = obj["return"];
string output1_param = jToken["output01"].ToString();
string output2_param = jToken["output02"].ToString();
Or work with Values of item, for example via First:
foreach (JToken item in jToken)
{
Console.WriteLine(item.First.ToString());
}
Also in this case casting to JProperty in foreach is also an option:
foreach (JProperty item in jToken)
{
Console.WriteLine($"{item.Name} - {item.Value}");
}
as you can see in This Link, indexer of JToken does not implemented and your code tries to using indexer of JToken.
When you call GetEnumerator of jToken, in this sample you will get just single element which is JProperty, so calling indexer of JProperty(by using string key) which implemented JToken will try using this indexer and throws exception.
what happens if you call using this way:
jToken["output01"].ToString();
in this pattern you are using indexer of JObject, which iterates over ChildrenTokens of JObject and give you values.
as Guru said you must read value using value field or use First element.

How to Read Name of array in from JObject in C#

This is the array that i am getting from an api response and I want to read "591460000000352107" this value. This is the key of array and that will be different in every response of api. so how can I read it from JObject in C#:
{"response": { "result": [{"591460000000352107": [{"Middle_Name": "","EmailID":"prateek.chauhan#gmail.com","Expertise": ""}]}]}}
var jobj = JObject.Parse(json);
foreach (var result in (jobj["response"]["result"]))
foreach (var key in (result as JObject).Properties())
Console.WriteLine(key.Name);
You can iterate over the results and get the name of the keys

How to get the deep level node value easily when we don't have the object class with fastjson

I need to parse lots of long json strings. Newtonsoft.Json is slow and I try to use fastjson.
I don't have the object class so I use the following code to get values when using Newtonsoft.Json:
JObject jo = (JObject)JsonConvert.DeserializeObject(addressBook);
string floor = jo["Street"]["building"]["floor"].ToString();
When I turn to use fastjson and use the JSON.Parse(string), I got an Dictionary<string, object>. And if I want to get the 'floor' value, I need to do the casting for each level like below:
var ob = (Dictionary<string, object>)JSON.Parse(addressBook);
var street = (Dictionary<string, object>)ob["Street"];
var building = (Dictionary<string, object>)street["building"];
var floor= (Dictionary<string, object>)building["floor"];
Does anyone know fastjson support it or not? And can it still be fast?

How to convert the following JSON array into IDictionary<string, object>?

Following is the serialized JSON array I want to convert to IDictionary
[
{
"8475": 25532
},
{
"243": 521
},
{
"3778": 15891
},
{
"3733": 15713
}
]
When I tried to use
JsonConvert.DeserializeObject<IDictionary<string, object>>((string)jarray);
I got an error saying:
Cannot cast 'jarray' (which has an actual type of 'Newtonsoft.Json.Linq.JArray') to 'string'
The JSON deserializer requires only a string.
If you already have the JArray, all you have to do is convert it to a dictionary I guess.
Roughly something like this:
IDictionary<string,object> dict = jarray.ToDictionary(k=>((JObject)k).Properties().First().Name, v=> v.Values().First().Value<object>());
Check this for complete code with an example
I think there might be a better way to convert it to a dictionary though. I'll keep looking.
the JsonConvert.DeserializeObject<T> Method takes a JSON string, in other words a serialized object.
You have a deserialized object, so you'll have to serialize it first, which is actually pointless, considering you have all the information you need right there in the JArray object. If you are aiming just to get the objects from the array as key value pairs, you can do something like this:
Dictionary<string, object> myDictionary = new Dictionary<string, object>();
foreach (JObject content in jarray.Children<JObject>())
{
foreach (JProperty prop in content.Properties())
{
myDictionary.Add(prop.Name, prop.Value);
}
}
To turn your JArray into a string, you'll need to assign the key & values of the dictionary for each element. Mario gave a very accurate approach. But there's a somewhat prettier approach as long as you know how to convert each item into your desired type. The below example is for Dictionary<string, string> but can be applied to any Value type.
//Dictionary<string, string>
var dict = jArray.First() //First() is only necessary if embedded in a json object
.Cast<JProperty>()
.ToDictionary(item => item.Name,
item => item.Value.ToString()); //can be modified for your desired type

Read and save unknown key value pair in JSON

I am making an API call. On successful completion I know the structure of JSON response. I can read that and save it on DB using JSON.NET, but if the API calls generates error, a JSON of unknown structure is generated. I have to parse and save it in DB. How can I do that.
In genral structure of error response is this:
{"origin-of_error":"error_message"}
There are some cases though where additional key value is also present.
Since you don't know the exact contents of the JSON, but you at least know it is a flat object with key-value pairs, then I would recommend deserializing into a Dictionary<string, string>. You can then easily iterate over the key-value pairs to extract the data you need to store in the DB.
string json = #"
{
""origin-of_error"" : ""error_message"",
""foo"" : ""bar""
}";
var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
foreach (KeyValuePair<string, string> kvp in dict)
{
Console.WriteLine(kvp.Key + ": " + kvp.Value);
}
try this
IDictionary<string, JToken> jsondata = JObject.Parse(json);
foreach (KeyValuePair<string, JToken> innerData in jsondata) {
Console.WriteLine("{0}=> {1}",innerData.Key, innerData.Value.ToString());
}

Categories

Resources