How to Read Name of array in from JObject in C# - 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

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 iterate through json array

How do we iterate through the Map array?
My payload looks like this:
{
"Record": "...bunch of hl7 data...",
"Map": [{ "DG1.2": "PatientDiag1" }, { "DG1.3": "PatientDiag2" }]
}
How do we iterate and parse the values of the Map array?
I've tried the following:
var blobObject = JObject.Parse(blob);
var map = blobObject["Map"]; //it's a JToken at this point
//now let's parse each key/value pair in the map:
foreach (var field in map)
{
var key = field.ToString();
var value = field[0].Value
}
"Map" is an array of JSON objects, so first you need to loop through the array, then you can loop through the key/value pairs of each object:
var blobObject = JObject.Parse(blob);
var map = blobObject["Map"]; //it's a JToken at this point
//now let's parse each key/value pair in the map:
foreach (var item in map.Cast<JObject>()) // Map is an array of objects so loop through the array, then loop through the key/value pairs of each object
{
foreach (var pair in item)
{
var key = pair.Key;
var value = pair.Value;
}
}
Or if you prefer to flatten the array with LINQ's SelectMany():
foreach (var pair in map.SelectMany(o => (IDictionary<string, JToken>)o))
{
var key = pair.Key;
var value = pair.Value;
}
Notes:
From the JSON spec
JSON is built on two structures:
A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
A JSON array is mapped to a JArray while a JSON object is mapped to a JObject.
How do we ... parse the values of the Map array? You don't need to parse the values of the Map array, they are already fully parsed. You just need to query them with LINQ to JSON.
Demo fiddle here.
var blobObject = JObject.Parse(blob);
var map = blobObject["Map"];
var values = map.Values().OfType<JProperty>();
foreach (JProperty prop in values)
{
Console.WriteLine(prop.Name); // property name
Console.WriteLine(prop.Value);// property value
}
Get all the values from Map key as JProperty, then loop through each property and you can access the property name using prop.Name and the value using prop.Value.

C# convert JSON to a JArray for an upload to Algolia

With the Algolia online cloud search engine their examples work fine.
// Load JSON file ( from file system )
StreamReader re = File.OpenText("contacts.json");
JsonTextReader reader = new JsonTextReader(re);
JArray batch = JArray.Load(reader);
// Add objects
Index index = client.InitIndex("contacts");
index.AddObjects(batch);
So what I am wanting to do it take C# class of properties that I serialized to JSON and be able to somehow use it as a JArray to load and add to send to Algolia.
// works fine
var json = new JavaScriptSerializer().Serialize(boom);
JArray batch = JArray.Parse(json); // breaks
Index index = client.InitIndex("myindex");
index.AddObjects(batch);
This breaks
JArray batch = JArray.Parse(json);
It's most likely failing because boom is not an array. What you can do is put boom in an anonymous array, and serialize that instead:
var json = new JavaScriptSerializer().Serialize(new[] { boom });
var batch = JArray.Parse(json);
Even better, you can skip over the serialization and create the JArray immediately from your object:
var batch = JArray.FromObject(new[] { boom });

Read JSON from string and get access to keys

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.
}

Getting the name / key of a JToken with JSON.net

I have some JSON that looks like this
[
{
"MobileSiteContent": {
"Culture": "en_au",
"Key": [
"NameOfKey1"
]
}
},
{
"PageContent": {
"Culture": "en_au",
"Page": [
"about-us/"
]
}
}
]
I parse this as a JArray:
var array = JArray.Parse(json);
Then, I loop over the array:
foreach (var content in array)
{
}
content is a JToken
How can I retrieve the "name" or "key" of each item?
For example, "MobileSiteContent" or "PageContent"
JToken is the base class for JObject, JArray, JProperty, JValue, etc. You can use the Children<T>() method to get a filtered list of a JToken's children that are of a certain type, for example JObject. Each JObject has a collection of JProperty objects, which can be accessed via the Properties() method. For each JProperty, you can get its Name. (Of course you can also get the Value if desired, which is another JToken.)
Putting it all together we have:
JArray array = JArray.Parse(json);
foreach (JObject content in array.Children<JObject>())
{
foreach (JProperty prop in content.Properties())
{
Console.WriteLine(prop.Name);
}
}
Output:
MobileSiteContent
PageContent
JObject obj = JObject.Parse(json);
var attributes = obj["parent"]["child"]...["your desired element"];
foreach (JProperty attributeProperty in attributes)
{
var attribute = attributes[attributeProperty.Name];
var my_data = attribute["your desired element"];
}
The default iterator for the JObject is as a dictionary iterating over key/value pairs.
JObject obj = JObject.Parse(response);
foreach (var pair in obj) {
Console.WriteLine (pair.Key);
}
Using Linq we can write something like:
JArray array = JArray.Parse(json);
foreach (JObject content in array.Children<JObject>())
{
List<string> keys = content.Properties().Select(p => p.Name).ToList();
}
If the JToken key name is unknown, and you only need the key's Value regardless of name, simply use the JToken.Values() method.
The below sample assumes the JToken value is a primitive type - first value found is extracted.
Solution can be extended to support Array values.
JToken fooToken = sourceData.
int someNum = fooToken .Values<int?>().First() ?? 0;
int someString = fooToken .Values<string>().First();
The simplest way is to look at the path of each item in the JSON object.
For Each token As JToken In json
Dim key= token.Path.Split(".").Last
Next

Categories

Resources