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
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 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.
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
I've spent MANY hours looking for the answer...
This is very easy in PHP but I just can't put it together in C#(I'm new to C# and mongo...)
I'm trying to iterate through all levels of a stored document. The document looks like this:
{
"_id": ObjectId("51f90101853bd88971ecdf27"),
"fields": [
{
"ID": ObjectId("51fd09498b080ee40c00514e"),
"NAME": "ID",
"TYPE": "Text"
},
{
"ID": ObjectId("51fd09a68b080ee40c0064db"),
"NAME": "Title",
"TYPE": "Text"
},
{
"ID": ObjectId("51fd09b28b080ee40c004d31"),
"NAME": "Start Date",
"TYPE": "Date"
},
{
"ID": ObjectId("51fd09c28b080ee40c007f2e"),
"NAME": "Long Description",
"TYPE": "Memo"
}
],
"name": "TODB",
"updated": "Wed Jul 31 2013 08:20:17 GMT-0400 (Eastern Daylight Time)"
}
I have no problem accessing the "name" and "updated" but can't figure out how to access the "fields" array.
Code so far :
{
MongoServer mongo = MongoServer.Create();
mongo.Connect();
var db = mongo.GetDatabase("forms");
mongo.RequestStart(db);
var collection = db.GetCollection("forms");
var query = new QueryDocument("name",
"TODB");
mongo.Disconnect();
}
#foreach(BsonDocument item in collection.Find(query))
{
#item.GetElement("name").Value
#item.GetElement("_id").Value
}
Again, I am able to access the name and _id just not any of the sub document values.
Thanks in advance for any assistance!
After I get the reading figured out, I am also going to want to write data....
There are a few ways, but here's one:
// build some test data
BsonArray dataFields = new BsonArray { new BsonDocument {
{ "ID" , ObjectId.GenerateNewId()}, { "NAME", "ID"}, {"TYPE", "Text"} } };
BsonDocument nested = new BsonDocument {
{ "name", "John Doe" },
{ "fields", dataFields },
{ "address", new BsonDocument {
{ "street", "123 Main St." },
{ "city", "Madison" },
{ "state", "WI" },
{ "zip", 53711}
}
}
};
// grab the address from the document,
// subdocs as a BsonDocument
var address = nested["address"].AsBsonDocument;
Console.WriteLine(address["city"].AsString);
// or, jump straight to the value ...
Console.WriteLine(nested["address"]["city"].AsString);
// loop through the fields array
var allFields = nested["fields"].AsBsonArray ;
foreach (var fields in allFields)
{
// grab a few of the fields:
Console.WriteLine("Name: {0}, Type: {1}",
fields["NAME"].AsString, fields["TYPE"].AsString);
}
You can often use the string indexer ["name-of-property"] to walk through the fields and sub document fields. Then, using the AsXYZ properties to cast the field value to a particular type as shown above.
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.