How do I append an JsonProperty to another JsonProperty - c#

I have this JsonDocument which looks like this
string jsonString = "{\"year\": 0, \"class\": [], \"schools\": []}";
JsonDocument newSchema = JsonDocument.Parse(jsonString)
And a bunch of JSON files, with these properties filed out.
Each of the JSON file have the same year, but contain information of one specific class and one specific school. None of the them is the same beside the year.
I trying to create a one JsonDocument with all class and schools put together into one JsonDocument, but seem to have a problem with appending the JsonProperty together..
This is what I have tried so far:
using (JsonDocument newSchema = JsonDocument.Parse(jsonString))
{
List<JsonProperty> properties = new List<JsonProperty>();
foreach(JsonProperty a in newSchema.RootElement.EnumerateObject())
{
properties.Add(a);
}
foreach (string classandSchoolDefinition in loadableSchemaDefinitions)
{
string schemaDefinitionAsJson = File.ReadAllText(classandSchoolDefinition );
JsonDocument schemaJson = JsonDocument.Parse(schemaDefinitionAsJson);
foreach (JsonProperty a in schemaJson.RootElement.EnumerateObject())
{
switch (a.Name)
{
case "year":
Console.WriteLine($#"({a.Name}+{a.Value}, {a.Value.ValueKind})");
break;
case "class":
Console.WriteLine($#"({a.Name}+{a.Value}, {a.Value.ValueKind})");
break;
case "school":
Console.WriteLine($#"({a.Name}+{a.Value}, {a.Value.ValueKind})");
break;
default:
break;
}
}
}
How do I concat each the Jsonproperty value to one combined newSchema, and not keep the into one?
In this case I only want append an array to another array.

You can reach this with Newtonsoft.Json
For example, you have
var o1 = JObject.Parse(#"{
'Name': 'Max',
'Enabled': false,
'Roles': [ 'User' ]
}");
and another object
var o2 = JObject.Parse(#"{
'Enabled': true,
'Roles': [ 'User', 'Admin' ]
}");
simply use Merge function like this -
o1.Merge(o2, new JsonMergeSettings
{
// to avoid duplicates
MergeArrayHandling = MergeArrayHandling.Union
});
the result will be -
{
"FirstName": "Max",
"Enabled": true,
"Roles": [
"User",
"Admin"
]
}

Related

Transform a JSON object to a JSON array, taking the first level of properties

I've this JSON object
{
"08f4f705-6e14-4781-8241-d04bf2dc6ada": {
"description": "xxxxxxxx",
"note": "yyyyyyyy"
},
"05f4f995-6e14-4567-8241-d04bf2d456ee": {
"description": "aaaaaa",
"note": "bbb"
},
"0675f995-6e14-4567-8241-d4567f2d456z": {
"description": "fffff",
"note": "gggg"
}
}
I need to convert into a JSON array like this:
(the elements should be the content of the first level properties)
[
{
"description": "xxxxxxxx",
"note": "yyyyyyyy"
},
{
"description": "aaaaaa",
"note": "bbb"
},
{
"description": "fffff",
"note": "gggg"
}
]
I can't manipulate the object and I didn't find an appropriate resource to follow. How can I do it?
You can achieve this by deserializing your json string into Dictionary<string, object>:
var obj = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
After that you extract the values and serialize them back to json:
var newJson = JsonConvert.SerializeObject(obj.Values);

How to use SelectToken to find value in nested dynamic JSON

I can't figure out how to use JToken to get the "Total Income" amount of "325.00".
I have tried quite a few different lines of code but seem to be missing something obvious.
{
"Rows": {
"Row": [
{
"Rows": {
},
"type": "Section",
"group": "Income",
"Summary": {
"ColData": [
{
"value": "Total Income"
},
{
"value": "325.00"
}
]
}
},
{
}
]
}
}
For the specific JSON sample that you have given in your question, you can extract the 325.00 value using SelectToken like this:
var obj = JObject.Parse(json);
var amount = (string)obj.SelectToken("Rows.Row[0].Summary.ColData[1].value");
Fiddle: https://dotnetfiddle.net/WRMAVu
If you want to extract both the label and the amount you can use SelectTokens instead with a wildcard for the ColData index:
var obj = JObject.Parse(json);
var values = obj.SelectTokens("Rows.Row[0].Summary.ColData[*].value")
.Select(t => (string)t)
.ToArray();
Fiddle: https://dotnetfiddle.net/DHZhS2

Accesing child value in JSON

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()));

deserialize json c# get value of variable

I deserialize JSON with Newtonsoft JSON DLL. I have next JSON answer
string answer = getjsonnanswer(url);
JObject a = JObject.Parse(answer);
How can I refer to a, that get 615 - Its value of variable in JSON answer, but it hasn't got a name.
{
"response": [615,
{
"body": "Привет) как жизнь?",
"title": "Re(2): ...",
"date": 1268238828,
"uid": 10024748,
"mid": 11056,
"read_state": 0,
"out":0
},
{
"body": "Жду :)",
"title": "Re(23): ...",
"date": 1268238448,
"uid": 27495120,
"mid": 11045,
"read_state": 1,
"out":1
}]
}
You just need to add the indexer to get the first item from the "response" array:
JObject a = JObject.Parse(answer);
var val = a["response"][0];
JObject a = JObject.Parse(answer);
JsonObject a = new JsonObject(answer);
JsonArray ss = (JsonArray)a["response"];
var result = ss[0];

JSON nested array

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.

Categories

Resources