DeserializeObject with newtonsoft.json without using Class - c#

I have this Joson
{
"Sucess": true,
"Msg": "OK",
"Ret": {
"First": 0,
"Next": true,
"Total": 60,
"Itens": [
{
"ID": 212121,
"Name": "uuuuuuuuuuuuuuuuuuuuuuuu",
"LcID": 9898,
"Oclao": false,
"Lal": {
"ID": 12202,
"Name": "pppppppppppppppppp",
"Pais": "Brasil",
"Dtc": 0.0
},
"Subtipo": {
"ID": 7458,
"Desc": "mnmnmnmnn"
},
"Tipo": {
"Sit": "cor1",
"Sitrm": 0,
"Name": "Shsdfow"
},
"Qtde": 0,
"Qntcoes": 0,
"Pubum": "adfsdfsdfs",
"Evias": {
"arq": {
"Mo": [
"site.com"
],
"Moir": [
"site.com"
]
}
}
},
{
"ID": 9797878,
"Name": "uuuuuuuuuuuuuuuuuuuuuuuu",
"LcID": 9898,
"Oclao": false,
"Lal": {
"ID": 12332,
"Name": "pppppppppppppppppp",
"Pais": "Brasil",
"Dtc": 0.0
},
"Subtipo": {
"ID": 7458,
"Desc": "mnmnmnmnn"
},
"Tipo": {
"Sit": "cor1",
"Sitrm": 0,
"Name": "Shsdfow"
},
"Qtde": 0,
"Qntcoes": 0,
"Pubum": "adfsdfsdfs",
"Evias": {
"arq": {
"Mo": [
"site.com"
],
"Moir": [
"site.com"
]
}
}
}
]
}
}
I would read the array "items" by the field names without using a class to Deserialize, what I did so far was:
JObject jRetorno = JObject.Parse(strJson);
IList<JToken> jItens = jRetorno["Itens"].Children().ToList();
The example http://www.newtonsoft.com/json/help/html/SerializingJSONFragments.htm that uses a class for this, as my json always changes, wanted something like:
strReturn = jItens[1]["ID"];
strReturn = jItens[1]["Name"];
strReturn = jItens[2]["ID"];
strReturn = jItens[2]["Name"];
strReturn = jItens[3]["ID"];
strReturn = jItens[3]["Name"];
Thanks!

You're not that far off. The data you want is one level further down, inside the Ret object. Try it like this:
JObject jRetorno = JObject.Parse(strJson);
IList<JToken> jItens = jRetorno["Ret"]["Itens"].Children().ToList();
foreach (JToken jt in jItens)
{
Console.WriteLine(jt["ID"]);
Console.WriteLine(jt["Name"]);
}
Fiddle: https://dotnetfiddle.net/TwtGyz

Related

How to add properties at runtime to JSON (C#)

Note: Im working with System.Text.Json package
Below is JSON I am getting from a database. I have to go through each of the keys in the JSON and check if there is a period (.) in the key name; if so, I need to add a property required with the value of true in the JSON in order to provide runtime validation:
validate:{"required", true}
Here is my JSON:
{
"display": "wizard",
"settings": {},
"components": [{
"title": "Event Information",
"label": "Event Information",
"type": "panel",
"key": "EventInformation",
"components": [{
"label": "Row1Columns",
"columns": [{
"components": [{
"label": "Event Date",
"format": "dd/MM/yyyy hh:mm a",
"tableView": false,
"datePicker": {
"disableWeekends": false,
"disableWeekdays": false
},
"validate": {
"unique": true
},
"key": "Event.EventDate",
"type": "datetime",
"input": true,
"suffix": "<i ref=\"icon\" class=\"fa fa-calendar\" style=\"\"></i>",
"widget": {
"type": "calendar",
"displayInTimezone": "viewer",
"language": "en",
"useLocaleSettings": false,
"allowInput": true,
"mode": "single",
"enableTime": true,
"noCalendar": false,
"format": "dd/MM/yyyy hh:mm a",
"hourIncrement": 1,
"minuteIncrement": 1,
"time_24hr": false,
"minDate": null,
"disableWeekends": false,
"disableWeekdays": false,
"maxDate": null
}
}],
"width": 6,
"offset": 0,
"push": 0,
"pull": 0
}, {
"components": [{
"label": "Duration (minutes)",
"mask": false,
"spellcheck": true,
"tableView": false,
"delimiter": false,
"requireDecimal": false,
"inputFormat": "plain",
"key": "Event.Duration",
"type": "number",
"input": true
}],
"width": 6,
"offset": 0,
"push": 0,
"pull": 0
}],
"tableView": false,
"key": "row1Columns",
"type": "columns",
"input": false
}, {
"label": "Row2Columns",
"columns": [{
"components": [{
"label": "Event Category",
"widget": "choicesjs",
"tableView": true,
"dataSrc": "custom",
"data": {
"custom": "values = getEventCategoryValues()"
},
"valueProperty": "AgencyEventCategoryId",
"template": "<span>{{ item.text }}</span>",
"selectThreshold": 0.3,
"validate": {
"required": true
},
"key": "Event.AgencyEventCategoryId",
"type": "select",
"indexeddb": {
"filter": {}
},
"input": true
}],
"width": 6,
"offset": 0,
"push": 0,
"pull": 0
}, {
"components": [{
"label": "Attendance",
"widget": "choicesjs",
"tableView": true,
"multiple": false,
"dataSrc": "custom",
"data": {
"custom": "values = getAttendanceValues()"
},
"valueProperty": "AgencyEventAttendanceId",
"template": "<span>{{ item.text }}</span>",
"selectThreshold": 0.3,
"validate": {
"required": true,
},
"key": "Event.AgencyEventAttendanceId",
"type": "select",
"indexeddb": {
"filter": {}
},
"input": true
}],
"width": 6,
"offset": 0,
"push": 0,
"pull": 0
}],
"tableView": false,
"key": "row2Columns",
"type": "columns",
"input": false
}, {
"label": "Event Options",
"widget": "choicesjs",
"tableView": true,
"multiple": true,
"dataSrc": "custom",
"data": {
"custom": "values = getEventManagerValues(data.Event.AgencyEventCategoryId)"
},
"template": "<span>{{ item.text }}</span>",
"refreshOn": "Event.AgencyEventCategoryId",
"clearOnRefresh": true,
"selectThreshold": 0.3,
"calculateServer": false,
"validate": {
"required": true,
"multiple": true
},
"key": "Event.EventDetail",
"type": "select",
"indexeddb": {
"filter": {}
},
"input": true
}, {
"label": "Casenote",
"wysiwyg": true,
"autoExpand": true,
"spellcheck": true,
"tableView": true,
"calculateServer": false,
"key": "Event.EventCasenote[0].Casenote",
"type": "textarea",
"input": true
}],
"input": false,
"tableView": false,
"breadcrumbClickable": true,
"buttonSettings": {
"previous": true,
"cancel": true,
"next": true
},
"collapsible": false
}]
}
One of the options would be to parse json into JObject and add property to it via Newtonsoft's Json.NET:
var obj = JObject.Parse("{'key':'value'}");
obj.Add("required", true);
Console.WriteLine(obj); // { "key": "value", "required": true }
To add new object you can use this overload of Add:
obj.Add("validate", JObject.FromObject(new { required = true }));
So the whole solution will look something like this:
var obj = JObect.Parse(your_json);
foreach(var token in obj.DescendantsAndSelf().ToList()) // ToList is important!!!
{
if(token is JObject xObj)
{
// check your conditions for adding property
// check if object does not have "validate" property
if(satisfies_all_conditions)
{
xObj.Add("validate", JObject.FromObject(new { required = true }));
}
}
}
I was having similar issue, and have found a solution, see below the code and comments. I am using Newtonsoft though but it is worth checking if you can use Newtonsoft library and have not found a solution for System.Text.Json.
All controls in your JSON are part of component object/array so we can use JSONPath, see the link for more details.
public void IterateJson(JObject obj, string mandatoryFieldKey)
{
JToken jTokenFoundForMandatoryField = obj.SelectToken
("$..components[?(#.key == '" + mandatoryFieldKey + "')]");
//Now we convert this oken into an object so that we can add properties/objects in it
if (jTokenFoundForMandatoryField is JObject jObjectForMandatoryField)
{
//We check if validate already exists for this field, if it does not
//exists then we add validate and required property inside the if condition
if (jObjectForMandatoryField["validate"] == null)
jObjectForMandatoryField.Add("validate",
JObject.FromObject(new { required = true })); //add validate and required property
else
{
//If validate does not exists then code comes here and
//we convert the validate into a JObject using is JObject statement
if (jObjectForMandatoryField["validate"] is JObject validateObject)
{
//We need to check if required property already exists,
//if it does not exists then we add it inside the if condition.
if (validateObject["required"] == null)
{
validateObject.Add("required", true); //add required property
}
}
}
}
}
It was interesting task for me, so this is what i have written
class Program
{
static void Main(string[] args)
{
string jsonFilePath = #"test.json"; //path to your json
string json = File.ReadAllText(jsonFilePath);
var data = JObject.Parse(json);
CheckJson(data);
Console.ReadLine();
}
static void CheckJson(JToken value)
{
if (value.Values().Count() != 0) //if more than 0 - so value is object or array and we have to call this method for each property
{
foreach (var item in value.Values().ToList())
{
CheckJson(item);
}
}
else if (true) //else - we have exactly value of key, which we can check, for example if . exists or additional checks
{
if (value.Parent.Parent is JObject jObject && jObject["validate"] == null) //check if above "required" property exists
{
jObject.Add("validate", JObject.FromObject(new { required = true })); //add required property
}
}
}
}
This code will add in each object property "required" if it is not exists.
All you need - just add Validation method and call it in if block.
And better to add additional validation that won't continue checking all properties if "required" property exists

How to upload/index a GeoJson file in Elasticsearch using NEST(C#)

I have GeoJson File with me which i want to index on Elastic Search through NEST
But Due to lack of expertise I am having trouble in indexing the document
I have created a class which represent the Mapping on ElasticSearch:
public class GeoDocument
{
[Nest.Keyword(Name = "DocId")]
public string DocId { get; set; }
[Nest.GeoShape(Name = "GeoField")]
public object GeoField { get; set; }
}
But when i use this Mapping to index a Document
var polygon = "{\"type\":\"Polygon\",\"coordinates\":[[[5.856956,51.002753],[5.856928,51.002771],[5.856687,51.002853],[5.856956,51.002753]]]}";
var geoDocument = new GeoJson
{
DocId = "1",
GeoField = JsonConvert.DeserializeObject<object>(polygon)
};
var IndexResponse = client.IndexDocument(geoDocument);
I get a Result Something like This
"_source": {
"DocId": "1",
"GeoField": [
[
[]
],
[
[
[
[
[],
[]
],
[
[],
[]
],
[
[],
[]
],
[
[],
[]
]
]
]
]
]
}
}
In order to make that JObject saved correctly, you have to tell the ElasticClient to use NewtonSoft .Net serializer.
Install NEST.JsonNetSerializer package
Reference the JsonNetSerializer in your ConnectionSettings
If you get 400 after changing the settings, you might need to create a new Index.
Sample code
using Nest;
using Elasticsearch.Net;
using Nest.JsonNetSerializer;
SingleNodeConnectionPool node = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
ConnectionSettings settings = new ConnectionSettings(
node,
JsonNetSerializer.Default
);
settings.DefaultMappingFor<GeoDocument>(m => m.IndexName("project2"));
ElasticClient client = new ElasticClient(settings);
// This is Supposed to be GeoDocument as per your question.
GeoDocument geoDocument = new GeoDocument
{
DocId = "1",
GeoField = JObject.Parse(polygon)
// GeoField = JsonConvert.DeserializeObject<object>(polygon) // <-- Works too.
};
IndexResponse IndexResponse = client.IndexDocument(geoDocument);
Response
{
"took": 1,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 1.0,
"hits": [
{
"_index": "project2",
"_type": "_doc",
"_id": "COQRXW8BNG2RJmIOyoO0",
"_score": 1.0,
"_source": {
"DocId": "1",
"GeoField": {
"type": "Polygon",
"coordinates": [
[
[
5.856956,
51.002753
],
[
5.856928,
51.002771
],
[
5.856687,
51.002853
],
[
5.856956,
51.002753
]
]
]
}
}
}
]
}
}

Unity Facebook SDK, retrieve data from 'apprequests' from API

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

Write to JArray in JObject

I have a JSON file.
{
"time": [
{
"id": "9999",
"name": "Foo",
"subitem": [
{
"name": "Bar",
"id": "99990",
"visible": true,
"subitem": [
{
"id": "999901",
"name": "Flex",
"visible": true
},
{
"name": "Bear",
"id": "999902",
"visible": true
},
{
"name": "James",
"id": "999903",
"visible": true
}
]
},
{
"name": "Smith",
"id": "999966",
"visible": true
},
{
"name": "John",
"id": "999933",
"visible": true
}
],
"visible": true
},
{
"name": "Doe",
"id": "1111",
"visible": true,
"subitem": [
{
"name": "Jack",
"id": "111111",
"visible": true
},
{
"name": "Wilson",
"id": "111188",
"visible": true
},
{
"name": "Andy",
"id": "111144",
"visible": true
},
{
"name": "Gibbs",
"id": "111155",
"visible": true
}
]
}
],
"name": "asdf",
"id": "13",
"visible": true
}
I also have a JObject and a method to get all the JSON data and store it in this object.
json1 = ti.GetTimeItems();
I have 2 methods in another class to write to the JSON file. Where datafolder is the path.
public void WriteToJson(JObject obj)
{
string fileName = dataFolder + "json1.json";
WriteToJson(fileName, obj);
}
private void WriteToJson(string fileName, JObject obj)
{
using (StreamWriter file = File.CreateText(fileName))
using (JsonTextWriter writer = new JsonTextWriter(file))
{
obj.WriteTo(writer);
}
}//end WriteToJson
Then i have a windows form where i want to take the text from 2 textboxes and add these to the JSON file.
Finally i have my click event
private void button1_Click_1(object sender, EventArgs e)
{
//string json = File.ReadAllText(url);
//JArray time = (JArray)json1.SelectToken("time");
json1.Add(new JObject(
new JProperty("name", textBoxName.Text),
new JProperty("id", textBoxId.Text),
new JProperty("visible", true)));
ti.WriteToJson(json1);
}
My problem is that i cannot seem to write to the array "time" in the JObject.
I managed to write to the file but in root instead of inside the array.
I have tried json1.SelectToken("time") and lots of different approaches, like this one http://stackoverflow.com/questions/15413825/how-do-you-add-a-jtoken-to-an-jobject#15782238 and also some approaches from the Newtonsoft documentation.
Any help is appriciated
Problem solved by ((JArray)json1.GetValue("time")). Selecting the array in the JObject json1 and adding to that instead of the root.
Hope this will help someone.
((JArray)json1.GetValue("time")).Add(
new JObject(
new JProperty("name", textBoxName.Text),
new JProperty("id", textBoxId.Text),
new JProperty("visible", true)));
ti.WriteToJson(json1);

get Specific Id from json file

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

Categories

Resources