I have a JSON object that looks like this
{
"totalCount": 2,
"students": [{
"name": "abc",
"data": {
"Maths": 20,
"Science": 25
},
"score": 10.0
},
{
"name": "xyz",
"data": {
"Maths": 44,
"Science": 12
},
"score": 11.0
}]
}
I want to deserialize this JSON object to an IEnumerable<String> that contains all the names.
I want -
private IEnumerable<String> GetAllNames(string json) to return ["abc","xyz"]
This is just sample data (and not homework!!). Any advice on how to achieve this would be appreciated. I'm using Newtonsoft library but haven't been able to do this effectively yet. I do not want to iterate through the objects and construct the list myself, any direct way of doing this?
EDIT -
This is what I'm doing currently
var studentList = new List<string>();
var json = JsonConvert.DeserializeObject<dynamic>(jsonString);
foreach (var data in json.students)
{
catalogsList.Add(data.name.toString());
}
return catalogsList;
Try this:
private IEnumerable<string> GetAllNames(string json)
{
JObject jo = JObject.Parse(json);
return jo["students"].Select(s => s["name"].ToString());
}
Related
I have a JSON response here,
{
"Items": [
{
"Key": {
"timestamp": "2022-11-06T20",
"value": 100.80
}
},
{
"Key": {
"timestamp": "2022-11-07T08",
"value": 100.90
}
}
]
}
That I would like to reformat to this:
{
"Key": [
{
"timestamp": "2019-01-08T20",
"value": 12.44
},
{
"timestamp": "2018-12-12 16:23:00",
"value": 12.45
}
]
}
For all responses, the Key must only be on the top once followed by an array of timestamps and values, and remove the Items parent value completely. I have tried doing this and messing around with the implementation, but I keep receiving multiple different errors. Is this the correct idea to do it or is there a better way to implement this?
JObject obj = JObject.Parse(jsonOutput);
JObject newObj = new JObject();
new JProperty("KEY", new JArray(
.Children<JProperty>()
.Select(j => new JObject(
new JProperty("timestamp", j.Value["timestamp"]),
new JProperty("value", j.Value["value"])
)
)
)
);
jsonOutput = newObj.ToString();
What is the correct way to implement this idea? Thanks!
This can be done very easily by combining
SelectTokens() with a JSONPath wildcard operator for the Items[*] array to select all required JSON objects.
Serialization of an anonymous type object to create the required output structure.
Thus:
var query = obj.SelectTokens("Items[*].Key");
jsonOutput = JsonConvert.SerializeObject(new { Key = query }, Formatting.Indented);
Demo fiddle here.
you can fixed it in one line
jsonOutput = new JObject {new JProperty("Key", ((JArray)JObject.Parse(jsonOutput)
["Items"]).Select(s => s["Key"]))}.ToString();
I want to create a method with the C# Newtonsoft library that can take in a parameter value to return the JSON data value, without needing to know and create a class beforehand, but all I can find are examples to deserialise into a class or into a dynamic object, both needing to know JSON structure prior at development time
Here's an example of what the kind of JSON format I'm expecting, but is subject to change:
{
"Input":
[
{
"Name": "foo"
},
{
"Name": "bar"
},
]
"Output":
[
{
"Name": "bob"
},
{
"Name": "builder"
},
]
}
I'm locked into using Newtonsoft library to work on the JSON file, or do it myself from scratch as it's an embedded system.
You can use JObject. If you deserialize a class without the type it will be deserialized to JObject. You would access your JObject values with named index which is obviously your property name. Other type of interest to you is JArray. This all resides in namespaces:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
Example:
So the example with your JSON would be:
var json = #"{
""Input"":
[
{ ""Name"": ""foo"" },
{ ""Name"": ""bar"" }
],
""Output"":
[
{ ""Name"": ""bob"" },
{""Name"": ""builder""}
]
}";
var obj = JsonConvert.DeserializeObject(json) as JObject;
var input = obj["Input"] as JArray;
var inputArray = input[0]["Name"];
This would get the first element in array that is in Input field - "foo".
How can i acces the first item id?
using (var http = new HttpClient())
{
var res = JArray.Parse(await http.GetStringAsync("http://api.champion.gg/champion/Gragas?api_key=????").ConfigureAwait(false));
^^^^^^ // Also tried with JObject instead of JArray, both don't work
var champion = (Uri.EscapeUriString(res[0]["items"][0]["mostGames"][0]["items"][0]["id"].ToString()));
Console.WriteLine(champion); // ^ [0] here because the JSON starts with an [
}
Example JSON result (made it smaller because the original JSON is over 21500 characters, made sure its valid with https://jsonlint.com, here is the original JSON response: https://hastebin.com/sacikozano.json)
[{
"key": "Gragas",
"role": "Jungle",
"overallPosition": {
"change": 1,
"position": 13
},
"items": {
"mostGames": {
"items": [{
"id": 1402,
"name": "Enchantment: Runic Echoes"
},
{
"id": 3158,
"name": "Ionian Boots of Lucidity"
},
{
"id": 3025,
"name": "Iceborn Gauntlet"
},
{
"id": 3065,
"name": "Spirit Visage"
},
{
"id": 3742,
"name": "Dead Man's Plate"
},
{
"id": 3026,
"name": "Guardian Angel"
}
],
"winPercent": 50.45,
"games": 300
}
}
}]
With JArray i get the following error: Accessed JObject values with invalid key value: 0. Object property name expected.
With JObject i get the following error: Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.
Thanks in advance, i hope i explained it well
It should be:
var champion = (Uri.EscapeUriString(res[0]["items"]["mostGames"]["items"][0]["id"].ToString()));
The outermost "items" property has a single object as its value, not an array, so [0] is not needed in ["items"][0]. Similarly "mostGames" has a single object value so the [0] is not needed in ["mostGames"][0].
Sample fiddle.
Note that if "items" is sometimes an array of objects, but sometimes is a single object instead of an array of one object, you can introduce the following extension method:
public static class JsonExtensions
{
public static IEnumerable<JToken> AsArray(this JToken item)
{
if (item is JArray)
return (JArray)item;
return new[] { item };
}
}
And do:
var champion = (Uri.EscapeUriString(res[0]["items"].AsArray().First()["mostGames"]["items"][0]["id"].ToString()));
i have json in object.
{
"data": [
{
"name": "Diljeet Jamwal",
"uid": 553042280,
"pic_square": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-ash4/274654_553042280_2105727599_q.jpg"
}, {
"name": "Jatinder Sharma",
"uid": 553042280,
"pic_square": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-ash4/274654_553042280_2105727599_q.jpg"
}]}
i want to show this in list in C#, how to do.
foreach (string data in yourlist)
{
console.WriteLine(data);
}
Of course do the parsing job to fill your list before ;)
You can try Newtonsoft.Json library http://nuget.org/packages/newtonsoft.json/
Example:
String yourdata = "..." // your JSON response
JObject json = JObject.Parse(yourdata);
after this, you can access your data:
String name = json["data"][0]["name"] //it should be Diljeet Jamwal
thanks to all, i have done this
dynamic array = JsonConvert.DeserializeObject(result.ToString());
foreach (var item in array)
{
foreach (var name in item["data"])
{
Response.Write(name["name"]);
}
}
using this
Lets say i have the following JSON
{
"data": [
{
"from": {
"name": "aaa bbb",
},
"actions": [
{
"name": "Comment",
"link": "http://...
},
{
"name": "Like",
"link": "http://.."
}
],
},
And i have
JSONObject wallData = helper.Get("/me/feed");
if (wallData != null)
{
var data = wallData.Dictionary["data"];
List<JSONObject> wallPosts = data.Array.ToList<JSONObject>();
}
foreach (Facebook.JSONObject wallItem in wallPosts)
{ ... }
Which stores me whole feed into wallData and 'data' object into wallPosts.
So then i can access the wallItem.Dictionary["from"].Dictionary["name"], and i get "aaa bbb".
But i can't get inside the actions array
The wallItem.Dictionary["actions"].Dictionary["name"] doesn't work.
Any idea
You need to do something like wallItem.Dictionary["actions"][0].Dictionary["name"] because "actions" is an array.
On a different note...its neater if u directly into a class...like this
var jSerializer = new JavaScriptSerializer();
var jsonObject = jSerializer.Deserialize<DataObject>(json);
The DataObject will be a class which emulates ur JSON data in a strongly typed class. Depending on the size of ur Json you will not have to use a lot of strings in your code.