I'm try to parse some JSON like this:
{
"results": [
"MLU413843206",
"MLU413841098",
"MLU413806325",
"MLU413850890",
"MLU413792303",
"MLU413843455",
"MLU413909270",
"MLU413921617",
"MLU413921983",
"MLU413924015",
"MLU413924085"
]
}
All is fine until I try to obtain the values themselves, for example:
// The JSON is shown above
var jsonResp = JObject.Parse(json);
var items = jsonResp["results"].Children();
I don't know how to obtain the values, each converted to string. Does somebody know how to do this?
You're halfway there. You can use the Select() method in the System.Linq namespace to project the IEnumerable<JToken> returned from the Children() method into an IEnumerable<string>. From there you can loop over the values using foreach, or put the values into a List<string> using ToList() (or both).
string json = #"
{
""results"": [
""MLU413843206"",
""MLU413841098"",
""MLU413806325"",
""MLU413850890"",
""MLU413792303"",
""MLU413843455"",
""MLU413909270"",
""MLU413921617"",
""MLU413921983"",
""MLU413924015"",
""MLU413924085""
]
}";
JObject jsonResp = JObject.Parse(json);
List<string> items = jsonResp["results"].Children()
.Select(t => t.ToString())
.ToList();
foreach (string item in items)
{
Console.WriteLine(item);
}
Fiddle: https://dotnetfiddle.net/Jcy8Ao
Related
I have a variety of input JSON formatted data which all contain a particular key-name terminalSize. This is the only piece I know. The total number of JSON trees or the exact depth of terminalSize inside the JSON tree will forever be an unknown and subject to change.
I'm looking for a C# solution to loop through every child of the JSON string and find terminalSize then fetch the value.
I've tried this with success but it will only work if terminalSize is in the first level of the JSON:
var list = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(jsonString);
var dict = list.SelectMany(d => d).ToDictionary(p => p.Key, p => p.Value);
var terminal = dict["terminalSize"];
Example 1.
{
"status": "success",
"data": {
"terminalSize": 3766505.46,
"totalTerminalSize": 3766505.46
},
"message": null
}
Example 2.
{
"lastUpdated": 1588020678,
"terminalData": {
"terminalSize": "451679852",
"totalTerminalSize": "2100000000"
},
"terminalValueSeries": {
"8x7": 2.33,
"8x6": 3.73,
"8x5": 4.49,
"8x4": 3.68,
"8x3": 13998,
"8x2": 274936,
"8x1": 5.09
}
}
Example 3.
{
"terminalSize": "492612346.17",
"terminalStatus": "online"
}
You can parse your JSON to a JToken, then use SelectToken with the recursive descent JsonPath operator .. to get the terminalSize anywhere in the JSON:
var terminalSize = (double?) JToken.Parse(json).SelectToken("$..terminalSize");
Fiddle: https://dotnetfiddle.net/5ziYbP
If there might be multiple terminalSize keys in the JSON, for example if you had an array of terminals, you can use SelectTokens instead and put the terminal sizes into a Dictionary keyed by path:
var sizes = JToken.Parse(json4)
.SelectTokens("$..terminalSize")
.ToDictionary(t => t.Path, t => (double)t);
Fiddle: https://dotnetfiddle.net/ivSM88
You could also use linq and filter the JProperty collection based on JProperty.Name. For example
var result = JObject.Parse(jsonString)
.DescendantsAndSelf()
.OfType<JProperty>()
.Single(x=>x.Name.Equals("terminalSize"))
.Value;
You may parse your JSON into JObject, then recursively go through all properties and sub objects to find a terminalSize value. There is no need to deserialize the entire JSON into specific object
var json = JObject.Parse(jsonString);
var result = GetTerminalSize(json);
double GetTerminalSize(JObject input)
{
foreach (var property in input.Properties())
{
if (property.Name == "terminalSize")
return property.Value.Value<double>();
if (property.Value.Type == JTokenType.Object)
return GetTerminalSize((JObject) property.Value);
//not sure, if the is a need to handle an array
if (property.Value.Type == JTokenType.Array)
foreach (var item in (JArray) property.Value)
return GetTerminalSize((JObject) item);
}
return 0;
}
It returns a correct value for all 3 examples
How do I convert a JSON array like this
[{"myKey":"myValue"},
{"anotherKey":"anotherValue"}]
to a C# Dictionary with json.net or system classes.
json.net can serialize directly to a dictionary, but only if you feed it an object, not an array.
Maybe converting to array of KeyValuePairs will help
using System.Linq;
var list = JsonConvert.DeserializeObject<IEnumerable<KeyValuePair<string, string>>>(jsonContent);
var dictionary = list.ToDictionary(x => x.Key, x => x.Value);
For anyone interested - this works, too:
Example JSON:
[{"device_id":"VC2","command":6,"command_args":"test args10"},
{"device_id":"VC2","command":3,"command_args":"test args9"}]
C#:
JsonConvert.DeserializeObject<List<JObject>>(json)
.Select(x => x?.ToObject<Dictionary<string, string>>())
.ToList()
Its quite simple actually :
lets say you get your json in a string like :
string jsonString = #"[{"myKey":"myValue"},
{"anotherKey":"anotherValue"}]";
then you can deserialize it using JSON.NET as follows:
JArray a = JArray.Parse(jsonString);
// dictionary hold the key-value pairs now
Dictionary<string, string> dict = new Dictionary<string, string>();
foreach (JObject o in a.Children<JObject>())
{
foreach (JProperty p in o.Properties())
{
string name = p.Name;
string value = (string)p.Value;
dict.Add(name,value);
}
}
I found that using a list of KeyValuePairs didn't work. I got the right number of elements but they had null Keys and Values.
In the end the only solution that worked for me was deserialising to a list of dictionaries (which each had a single kvp element).
The data must to be sent as follows (format):
"Values": [
{"Key" : "abc" , "Value": 23.14},
{"Key" : "abc1" , "Value": 23.11},
{"Key" : "abc2" , "Value": 23.17},
{"Key" : "abc3" , "Value": 23.19}
]
thereby, the converting process will work. It worked fine to me in my attempt to convert from JSON to dictionary<string,decimal>
Since you can only deserialize from an object, do just that by manipulating the JSON string a little first. Wrap it in an object:
json = String.Format("{{\"result\":{0}}}", json);
I have a JSON file I'm reading from text and parsing it into JObject using Newtonsoft.Json.Linq. The JSON file looks like this:
{
"EntityTypeDto":[
{
"EntityType":"Grade",
"Language":"ES"
},
{
"EntityType":"ApplicationType",
"Language":"ES"
},
{
"EntityType":"Borough",
"Language":"ES"
}
]
}
Using the Newtonsoft library, are there any methods I can leverage on JObject to replace the Language property of all the objects to another value? If not what would be another way to do this? This project is a console application in C#, VS 2012, thanks.
You don't need Linq here to achieve what you need , Linq is for consult data, not for modify it. So you can just, eg, a foreach to iterate and modify the elements of the array:
JObject json= JObject.Parse(jsonString);
JArray entityTypeDtos= (JArray)json["EntityTypeDto"];
foreach(var e in entityTypeDtos)
{
if(e["Language"] != null)
e["Language"]="EN";
}
I'm guessing by the Linq tag you would like a Linq approach try this
string json = #"{
'EntityTypeDto':[
{
'EntityType':'Grade',
'Language':'ES'
},
{
'EntityType':'ApplicationType',
'Language':'ES'
},
{
'EntityType':'Borough',
'Language':'ES'
}
]
}";
JObject myjobj = JObject.Parse(json);
JArray EntityType = (JArray)myjobj["EntityTypeDto"];
(from eobj in EntityType
where eobj["Language"]="ES"
select eobj).ForEach(x => x["Language"]="New Value");
I have a json file that i read to string and then convert to a jobject. I get a JToken from this object by selecting one of its children.
I want to list this JTokens children in a Listbox. I think, to do this i need to convert th eJTOken to a ListItem - how can i do this? If there is a better alternative way then would be interested to hear it!
string filePath = #"C:\output.json";
JObject json = JObject.Parse(System.IO.File.ReadAllText(filePath));
JToken jsonFiles = json["Files"];
jsonFilesListItem = ....
JsonListBox.Items.Add(jsonFilesListItem);
Assuming that json["Files"] contains a simple array of strings, all you have to do is use a foreach loop, as shown in the example below:
string jsonString = #"
{
""Files"": [
""foo.xml"",
""bar.txt"",
""baz.jpg"",
""quux.wav""
]
}";
JObject json = JObject.Parse(jsonString);
JToken jsonFiles = json["Files"];
foreach (string fileName in jsonFiles)
{
JsonListBox.Items.Add(fileName);
}
I have the following JSOn I need to parse:
{"items":[{"dict":"es","words":[{"word":"car","id":"3487"},{"word":"dog","id":"443"},{"word":"plane","id":"1171"}]},{"dict":"fr","words":[{"word":"house","id":"134"}]}]}
Using JavaScriptSerializer, how could I iterate first through each dict and then retrieve the id of each word?
make anonymouse type, acording your json, for example:
var result = new[] {new {action = "", value = false}}; // put your item structure here
var list = JsonConvert.DeserializeObject(myJson, result.GetType());
then you might want to itterate through. For example:
foreach (dynamic val in ((dynamic) list)) { ...