Reformatting a JSON in C# - c#

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

Related

Serializing c# class to JSON string with custom column name

I have this result
{
"StatusCode": "200",
"Description": "Success",
"Data": [
{
"Language_Key": "btn_select_country",
"En_Val": "SELECT COUNTRY",
"Ar_Val": "اختر الدولة"
},
{
"Language_Key": "btn_continue",
"En_Val": "CONTINUE",
"Ar_Val": "استمرار"
}
]
}
I would like to achieve below result.
{
"StatusCode":"200",
"Description":"Success",
"Data":{
"btn_select_country":{
"En_Val":"SELECT COUNTRY",
"Ar_Val":"اختر الدولة"
},
"btn_continue":{
"En_Val":"CONTINUE",
"Ar_Val":"استمرار"
}
}
}
I want Language_Key to replace with column name and with 2 child nodes as EN and AR below is my code
Any hint is appreciated. Thanks
you serialize a dictionary where the key is your Language_Key:
Dictionary<string, Translation> dict = countryObj
.ToDictionary(o => o.Language_Key, o => new Translation { Ar_Val = o.Ar_Val, En_Val = o.En_Val});
rs.Data = dict;
json = new JavScriptSerializer().Serialize(rs);
You can use JsonProperty Attribute to rename properties after they get serialize.
https://www.newtonsoft.com/json/help/html/JsonPropertyName.htm

Json String parse into Dictionary key value pairs c#

I am trying the convert my json string into dictionary but could not successful.
{
"healths": [
{
"serviceName": "UserMgt",
"subService": [
{
"subServiceName": "Base",
"status": 10
},
{
"subServiceName": "Url",
"description": "Url is bad",
"status": 10
},
{
"subServiceName": "Configuration",
"status": 2
}
]
},
{
"serviceName": "ConfigurationMgt",
"subService": [
{
"subServiceName": "url",
"description": "urlis OK!",
"status": 2
},
{
"subServiceName": "Configuration Db",
"status": 2
}
]
}
}...and so son
So, as you see we have a service name, and based on that we have subserviceName then again service name and subservicename.Basiclly i want to convert this into dictionary as a key-value pair so that based on the key(service) we have values subservice(again a key value pair).
I tried many things but does not get a proper result.
like for example using newtonsoft nuget.
JObject jsonObj = JObject.Parse(formattedJson);
Dictionary<string, object> dictObj = jsonObj.ToObject<Dictionary<string, object>>();
foreach(var kv in dictObj)
{
Console.WriteLine(kv.Key + "::::" + kv.Value);
}
In this scenario I am getting output like key as a healths and every thing as a value.
Can anyone please help me regarding this.The Json and c# is new for me.
Thanks In Advance.
Assuming that you are guaranteed to have the described structure, you can deserialize to JObject and use LINQ's ToDictionary to process it:
var dict = JsonConvert.DeserializeObject<JObject>(json)["healths"]
.ToDictionary(
s => s["serviceName"].ToString(),
s => s["subService"]
.ToDictionary(ss => ss["subServiceName"].ToString(), ss => ss["status"].ToString()));
Where you can change ss => ss["status"].ToString() to select what is actually needed as subService value.

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

Customise Default Output Of JSON in MVC C#

I am using dynamic ExpandoObject() to create some json required for an NVD3/d3.js visualisation.
The nvd3 library is pretty explicit in what it needs with regards to data identifiers.
Exactly the json i need is the following -
[{
key: "AgeGroups",
values: [{
"label": "<20",
"value": 0
}, {
"label": ">20 <29",
"value": 160
}, {
"label": ">29 <39",
"value": 240
}]
}]
Note: the string 'key' must be lowercase and values must be pluralized.
With the following c#, I am able to get very close -
ageDemoJson.AgeGroups = new object[]
{
new { label = "<20", value = lessThan20 },
new { label = ">20 <29", value = between20and29 },
new { label = ">29 <39", value = between29and39 },
};
This outputs the following
[{
Key: "AgeGroups",
Value: [{
"label": "<20",
"value": 0
}, {
"label": ">20 <29",
"value": 160
}, {
"label": ">29 <39",
"value": 240
}]
}]
With this output, I need to customise the default behaviour of ExpandoObject and make the string 'Key' become 'key' and the string 'value' become 'values'
Is there anyway of doing this?
Of course I can work around this by parsing the json to string and replacing what I need in javascript, but would like if I didn't have to do that.
If you're using asp.net core you can change the JSON serialization by adding this line:
services.AddMvc()
.AddJsonOptions(opts =>
{
// Force Camel Case to JSON
opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
Or you can achive the same result by using Newtonsoft's Json.NET with this option:
string json = JsonConvert.SerializeObject(
yourObjectToSerialize,
new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }
);

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