I have following json object of array structure.I am trying to retrieve certain elements from array of objects
{
"data": [
{
"_id": "5b62dc6ebef986403db8aafd",
"name": "smitha vijaya",
"designation": "account management",
"projects": {
"project1": "description1",
"project2": "description2"
},
"age": "27"
},
{
"_id": "5b62dd17bef986403db8ab90",
"name": "JIKKU VARGHESE",
"designation": "SUPERVISING OPERATIONS MANAGER",
"projects": {
"project1": "description1",
"project2": "description2"
},
"age": "27"
},
{
"_id": "5b62dd76bef986403db8abe3",
"name": "SUJEETH NAIR",
"designation": "MENA AMS",
"projects": {
"project1": "description1",
"project2": "description2"
},
"age": "30"
},
{
"_id": "5b62ddb1bef986403db8ac13",
"name": "GIRISH KN",
"designation": "MENA AMS",
"projects": {
"project1": "description1",
"project2": "description2"
},
"age": "27"
}
]
}
I am using following c# code to extract ist name (smitha)
JsonData jsonvale = JsonMapper.ToObject( jsonString);
Name = jsonvale["data"][0]["name"].ToString();
print (name);
how can i acces other elements like name jikku and so on?
You could iterate using a for loop:
for(int i = 0; i < jsonvale.length; i++) {
JsonData jsonvale = JsonMapper.ToObject(jsonString);
Name = jsonvale["data"][i]["name"].ToString();
print(name);
}
You can iterate it over your json array like following:
JsonData jsonvale = JsonMapper.ToObject( jsonString);
for (var i=0; i<jsonvale.length; i++){
print(jsonvale["data"][i]["name"].ToString());
}
Just deserialize this json in List() and then you can access all data from this list without loops, and when you do not need this list anymore, you can destroy it. See this example https://github.com/IonCojucovschi/JsonDeserializeGenericForm
Related
I am fetching /me/apprequests from Facebook API. It works and I get the data in JSON format.
Thing is that everything is nested, like a dictionary inside a dictionary.
What i tried:
Dictionary<string, object> dict = Facebook.MiniJSON.Json.Deserialize(result.RawResult) as Dictionary<string, object>;
object data;
string request_code = "";
if (dict.TryGetValue("data", out data))
{
var rc = (((Dictionary<string, object>)data)["id"]);
request_code = (string)rc;
}
Debug.Log("request_code=" + request_code);
I think I need to loop the dictionary to get all id's.
I can confirm that if (dict.TryGetValue("data", out data)) does work correctly and get the dictionary of data arrays, but fails here (((Dictionary<string, object>)data)["id"]); with casting error.
Json looks like:
{
"data": [{
"application": {
"category": "Games",
"link": "https:\/\/www.facebook.com\/games\/?app_id=2523532533",
"name": "game name",
"id": "23432423423"
},
"created_time": "2019-02-27T16:01:15+0000",
"from": {
"name": "David boom",
"id": "387923432423089962"
},
"message": "You are invited",
"to": {
"name": "Dusty Spice",
"id": "10234324421033685"
},
"id": "413880842521239_10156578101000000"
},
{
"application": {
"category": "Games",
"link": "https:\/\/www.facebook.com\/games\/?app_id=2523532533",
"name": "game name",
"id": "23432423423"
},
"created_time": "2019-02-27T14:12:41+0000",
"from": {
"name": "David boom2",
"id": "387923432423089962"
},
"message": "You are invited",
"to": {
"name": "Dusty Spice",
"id": "10234324421033685"
},
"id": "316676422209302_10156578101000000"
}],
"paging": {
"cursors": {
"before": "NDEzODgwODQyNTIxMjM5Ojc1OTQzODY4NAZDZD",
"after": "MzE2Njc2NDIyMjA5MzAyOjc1OTQzODY4NAZDZD"
}
}
}
Managed to make it work if it will help someone:
string request_code = "";
if (dict.TryGetValue("data", out data))
{
int dataLength = ((List<object>)data).Count;
for (int i = 0; i < dataLength; i++)
{
var rc = ((List<object>)data)[i];
var rc2 = (((Dictionary<string, object>)rc)["id"]);
request_code = (string)rc2;
Debug.Log("request_code=" + request_code);
}
}
I have the following set of variable JSON data where the first row is the list of element names and the other rows represent the list of element values:
[
[
"category",
"author",
"title",
"price"
],
[
"reference",
"Nigel Rees",
"Sayings of the Century",
"8.95"
],
[
"fiction",
"Evelyn Waugh",
"Sword of Honour",
"12.99"
],
[
"fiction",
"Herman Melville",
"Moby Dick",
"8.99"
],
[
"fiction",
"J. R. R. Tolkien",
"The Lord of the Rings",
"22.99"
]
]
I want to build the following type of JSON object from the data:
{
"book": [
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{
"category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
]
}
How can I build my JSON object which should be identical to the above. I don't see any direct support for doing this using JSON.NET APIs.
Any help is greatly appreciated.
This is just an idea to get you on the right track.
JObject obj = new JObject();
var child = new JArray();
var child2 = new JObject();
child2.Add("category", "references");
child.Add(child2);
obj.Add("book", child);
var result = obj.ToString();
I won't do the string parsing for you, i think you should be able to handle that.
The piece of code I've given produces the following JSON:
{
"book": [
{
"category": "references"
}
]
}
Hope this helps.
You can do this transformation using Json.Net's LINQ-to-JSON API:
JArray array = JArray.Parse(origJson);
string[] keys = array.First().Select(t => t.ToString()).ToArray();
JArray array2 =
new JArray(array.Skip(1).Select(a =>
new JObject(a.Select((t, i) =>
new JProperty(keys[i], t)
))
));
JObject obj = new JObject(new JProperty("book", array2));
string finalJson = obj.ToString();
Fiddle: https://dotnetfiddle.net/kMyHOe
this is my json file
{
{
"#odata.context": "https://api.onedrive.com/v1.0/$metadata#drives('me')/items('root')/children/$entity",
"createdBy": {
"application": {
"displayName": "Nopbackup",
"id": "4c190e01"
},
"user": {
"displayName": "pallav jha",
"id": "611c19eb038d5aa1"
}
},
"createdDateTime": "2016-05-12T07:25:36.463Z",
"cTag": "adDo2MTFDMTlFQjAzOEQ1QUExITEyNC42MzU5ODYzODk5MTI3MDAwMDA",
"eTag": "aNjExQzE5RUIwMzhENUFBMSExMjQuMw",
"id": "611C19EB038D5AA1!124",
"lastModifiedBy": {
"application": {
"displayName": "Nopbackup",
"id": "4c190e01"
},
"user": {
"displayName": "pallav jha",
"id": "611c19eb038d5aa1"
}
},
"lastModifiedDateTime": "2016-05-12T08:36:31.27Z",
"name": "Nopbackup",
"parentReference": {
"driveId": "611c19eb038d5aa1",
"id": "611C19EB038D5AA1!105",
"path": "/drive/root:"
},
"size": 0,
"webUrl": "https://onedrive.live.com/redir?resid=611C19EB038D5AA1!124",
"fileSystemInfo": {
"createdDateTime": "2016-05-12T07:25:36.463Z",
"lastModifiedDateTime": "2016-05-12T08:36:31.27Z"
},
"folder": {
"childCount": 0
}
}
}
i want to get this "id": "4c190e01" from json
dynamic value = Newtonsoft.Json.JsonConvert.DeserializeObject(result);
string id = Convert.ToString(value.id[0]);
this is my code but i am not getting 4c190e01 id
rewrite your code as following...
dynamic valuePoco = Newtonsoft.Json.JsonConvert.DeserializeObject(result);
string id = Convert.ToString(valuePoco.createdBy.application.id);
You can use the path to the desired property. If you want to select the element with 4c190e01 as id, you can use
string id = value.createdBy.application.id;
or
string id = value.lastModifiedBy.application.id;
depending on your needs.
As it was pointed out, you'd need to fix your JSON first and remove the first { and the last }
First thing first, Your json is invalid.
You've to remove one { from top and } from the bottom and then use the following code:
dynamic jsonObj = JsonConvert.DeserializeObject(result);
string id = jsonObj.createdBy.application.id.ToString();
I have two json strings I want to compare.
The problem is that when the properties are the same but in a different order.
Simple example:
{
"Number": "123",
"Name": "My name",
"FirstName": "My First name",
"Prop1": false,
"Prop2": [],
"Plans": [],
"SomeList": [
{
"Code": "118",
"Period": {
"From": "2000-01-27T00:00:00.0000000",
"Until": "2003-12-31T00:00:00.0000000"
}
},
{
"Code": "120",
"Period": {
"From": "2004-01-01T00:00:00.0000000",
"Until": "2004-12-31T00:00:00.0000000"
}
}
]
}
and
{
"Number": "123",
"FirstName": "My First name",
"Name": "My name",
"Prop1": false,
"Prop2": [],
"Plans": [],
"SomeList": [
{
"Code": "120",
"Period": {
"From": "2004-01-01T00:00:00.0000000",
"Until": "2004-12-31T00:00:00.0000000"
}
},
{
"Code": "118",
"Period": {
"From": "2000-01-27T00:00:00.0000000",
"Until": "2003-12-31T00:00:00.0000000"
}
}
]
}
These two json's are equal.
The compare function JToken.DeepEquals says it's not equal.
And I don't want to serialize to an object XYZ to compare both jsons.
I want to sort the properties of the json so the JToken.DeepEquals works fine.
The following code:
var data = _context.People.ToList(); //_context is my DataContext.
produces the result:
[{ "name": "john", "age": "30" }, { "name": "jane", "age": "31" }]
but, I want it to be a dictionary, so something like:
{ "xldata" : [{ "name": "john", "age": "30" }, { "name": "jane", "age": "31" }] }
I got it to work by doing:
Dictionary<string,List<People>> vals = new Dictionary<string, List<People>>();
vals.Add("xldata", people);
but, my dictionary's value is System.Object[] instead of the people
The purpose of this is to export data, so when I get to this line:
var people = jss.Deserialize<List<People>>(args["xldata"]);
args["xldata"] is `System.Object[]` and it says `Invalid JSON primitive`.
Here is the script is supposed to export the data to excel:
$.post(urlContent + exportHandlerPath, Json, function(data) {
var viewData = {};
viewData.xldata = JSON.stringify(data);
html = ich.excelExportTemplate(viewData);
$excelExportContainer.html(html);
var input = $excelExportContainer.find('input#excelExportHiddenField');
input.val(viewData.xldata);
var $excelForm = $('#excelExportForm');
$excelForm.attr('action', '/People/ExportToExcel/');
$excelForm.submit();
}
Apparently your args["xldata"] does not contain a json string like [{ "name": "john", "age": "30" }, { "name": "jane", "age": "31" }], but something returned by a .net object .ToString().
With JavaScriptSerializer.Deserialize you can only deserialize json represenations.