How to get a specific field from json object by key:value? - c#

I'm trying to save my data using json. I don't know how to get specific object group from a set of json objects.
[
{
"dateinformation": "2021-10-05:23:01",
"id": 1,
"MoveCount": 3,
"StartPoint": 2322,
"TotalDist": 2331,
"SafeDist": 21332,
"Feed": 2332,
"EndPoint":23245,
"Count":1221,
},
{
"dateinformation": "2021-10-05:26:01",
"id": 2,
"MoveCount": 3,
"StartPoint": 2322,
"TotalDist": 2331,
"SafeDist": 21332,
"Feed": 2332,
"EndPoint":23245,
"Count":1221,
},
{
"dateinformation": "2021-10-55:03:01",
"id": 3,
"MoveCount": 3,
"StartPoint": 2322,
"TotalDist": 2331,
"SafeDist": 21332,
"Feed": 2332,
"EndPoint":23245,
"Count":1221,
}]
is it possible to get/delete a specific object from a bundle of json object by its "id" value?

Do like that
NameSpace will include:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
Here you can replace your id by specificId
List<Root> myDeserializedClass = JsonConvert.DeserializeObject<List<Root>>(myJsonResponse); // myJsonResponse is My Source Json
int specificId = 123; // my dynamic
var specficObject = myDeserializedClass.Where(x => x.id == specificId);
Class for Deserialize your JSON response:
public class Root
{
public string dateinformation { get; set; }
public int id { get; set; }
public int MoveCount { get; set; }
public int StartPoint { get; set; }
public int TotalDist { get; set; }
public int SafeDist { get; set; }
public int Feed { get; set; }
public int EndPoint { get; set; }
public int Count { get; set; }
}
Also, I have noticed your JSON last column comma in last that should not be like that "Count" : 1221,

Related

How to parse json with an array into object

Consider the following json:
{
"0": {
"id": "1",
"email": "someemail#test.com",
"tstamp": "2019-01-21 11:19:48",
"times": "2",
"tstamp_iso": "2019-01-21T12:19:48-05:00"
},
"1": {
"id": "2",
"email": "someotheremail#test.com",
"tstamp": "2019-01-21 11:25:48",
"times": "2",
"tstamp_iso": "2019-01-21T12:25:48-05:00"
},
"result_code": 1,
"result_message": "Success!",
"result_output": "json"
}
I am trying to convert that data into a c# object, however, I'm not sure how to go about the array value as it has 0, 1 for its name instead of it being nested in an array and it will go on up until 20 if there are 20 results. I can't change the json data.
I got this far:
[JsonObject]
public class FirstObject
{
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "email")]
public string Email { get; set; }
[JsonProperty(PropertyName = "tstamp")]
public string TimeStamp { get; set; }
[JsonProperty(PropertyName = "times")]
public string Times { get; set; }
[JsonProperty(PropertyName = "tstamp_iso")]
public string TimeStampIso { get; set; }
}
[JsonObject]
public class SecondObject
{
public FirstObject[] FirstObjects { get; set; }
[JsonProperty(PropertyName = "result_code")]
public string ResultCode { get; set; }
[JsonProperty(PropertyName = "result_message")]
public string ResultMessage { get; set; }
[JsonProperty(PropertyName = "result_output")]
public string ResultOutput { get; set; }
}
What I don't understand is how to map FirstObjects to results of 0, 1, ... 20. I am hoping there is a better way than writing out that 20 times and setting the name to 0, or 1, etc...
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
namespace ConsoleApp2
{
class Program
{
const string json = #"{
""0"": {
""id"": ""1"",
""email"": ""someemail#test.com"",
""tstamp"": ""2019-01-21 11:19:48"",
""times"": ""2"",
""tstamp_iso"": ""2019-01-21T12:19:48-05:00""
},
""1"": {
""id"": ""2"",
""email"": ""someotheremail#test.com"",
""tstamp"": ""2019-01-21 11:25:48"",
""times"": ""2"",
""tstamp_iso"": ""2019-01-21T12:25:48-05:00""
},
""result_code"": 1,
""result_message"": ""Success!"",
""result_output"": ""json""
}";
static void Main(string[] args)
{
JObject o = JObject.Parse(json);
List<FirstObject> l = new List<FirstObject>();
int c = 0;
while (o[$"{c}"] != null)
{
FirstObject fo = o[$"{c++}"].ToObject<FirstObject>();
l.Add(fo);
}
SecondObject so = JsonConvert.DeserializeObject<SecondObject>(json);
so.FirstObjects = l.ToArray();
Console.ReadKey();
}
}
}

Error while de-serializing json array [duplicate]

This question already has answers here:
Serialize and Deserialize Json and Json Array in Unity
(9 answers)
Closed 4 years ago.
I'm trying to deserialize a Json string.
This is my code:
[System.Serializable]
public class SharedWorlds
{
public int worldId { get; set; }
public System.DateTime uploaded { get; set; }
public string username { get; set; }
public string levelName { get; set; }
public string gameVersion { get; set; }
public string description { get; set; }
public string filename { get; set; }
public string screenshot1 { get; set; }
public string screenshot2 { get; set; }
public string userTag { get; set; }
public string userURL { get; set; }
public double price { get; set; }
public int nrDownload { get; set; }
public int votes { get; set; }
}
[System.Serializable]
public class Record {
public List<SharedWorlds> record;
}
try {
SDE3D _webService = new SDE3D();
result= _webService.GetMassiveWorldsList ();
var records = JsonUtility.FromJson<Record>(result);
}
catch(System.Exception ex) {
Debug.Log (ex.Message.ToString ());
}
And this is my valid jSon (here two records, but I want to send many records per time).
[
{
"worldId": 5,
"uploaded": "/Date(1524875719000)/",
"username": "quik",
"levelName": "Station",
"gameVersion": "1.0.1",
"description": "iwoeijksf",
"filename": "0000003.dat",
"screenshot1": "0000003a.png",
"screenshot2": "0000003b.png",
"userTag": "",
"userURL": "",
"price": 0,
"nrDownload": 5,
"votes": 5
},
{
"worldId": 4,
"uploaded": "/Date(1524875659000)/",
"username": "aksio",
"levelName": "Garage",
"gameVersion": "1.0.1",
"description": "Adlkld",
"filename": "0000003.dat",
"screenshot1": "0000003a.png",
"screenshot2": "0000003b.png",
"userTag": "",
"userURL": "",
"price": 0,
"nrDownload": 4,
"votes": 4
}
]
I'm getting error:
"ArgumentException: JSON must represent an object type."
I'm pretty sure the error is in this code line:
var records = JsonUtility.FromJson<Record>(result);
How to deserialize an array of json object ?
Thanks
Because your JSON data is not a Record. It's a collection of SharedWorlds. So something like this:
var sharedWorlds = JsonUtility.FromJson<SharedWorld[]>(result);
Or perhaps:
var sharedWorlds = JsonUtility.FromJson<List<SharedWorld>>(result);
From which you could create a Record:
var record = new Record { record = sharedWorlds };
If the JSON needs to deserialize into a Record then it would need to be in the format of a Record object:
{
"record":
[
/* the rest of your JSON within the square brackets */
]
}
Then it would be a Record:
var record = JsonUtility.FromJson<Record>(result);
*Side note: Your class and variable names and the pluralizations you're using are really confusing. The semantics of which is probably not making your debugging any easier for you.
You get to script collection of object no one single object in your JSON

c# Deserializing nested Json

This is the Json I am trying to parse/deserialize
{
"transactionId": "c34625a5-0590-48aa-8d1a-978df9aa9010",
"dal": {
"HourlyForecast": {
"geocode:40.77,-73.96:language:en-US:units:e": {
"data": {
"id": "40.77,-73.96",
"vt1hourlyForecast": [{
"processTime": "2017-07-12T12:00:00-0400",
"temperature": 85,
"precipPct": 15,
"precipType": "rain",
"uvIndex": 8,
"icon": 30,
"iconExtended": 3000,
"windDirCompass": "WSW",
"windDirDegrees": 253,
"windSpeed": 6,
"phrase": "Partly Cloudy",
"dayInd": "D",
"severity": 1,
"rh": 62,
"feelsLike": 92
}
//rest of json
I need to access vt1hourlyForecast[]
I've tried the dynamic JObject approach here
dynamic hourlydata = JObject.Parse(jsonData);
string hourlyForecast = hourlydata["Vt1hourlyForecast"].ToString();
Console.WriteLine(hourlydata);
But I get the error "Cannot perform runtime binding on a null reference"
I am really stuck on how to properly parse this. I have read a lot of similar questions but the nested Json is really confusing me any help will be greatly appreciated.
You need to navigate to the list property vt1hourlyForecast, since it's not a property of the outer object, but of a nested property e.g.
JObject jObject = JObject.Parse(json);
var dal = jObject["dal"];
var hourlyForecast = dal["HourlyForecast"];
var geocode = hourlyForecast["geocode:40.77,-73.96:language:en-US:units:e"];
var data = geocode["data"];
JArray forecast= (JArray)data["vt1hourlyForecast"];
foreach (JProperty forecastProperty in forecast)
{
Console.WriteLine(forecastProperty.Value);
}
In the example code I'm just casting the property to a JArray to show that that's possible, and it's enumerable.
Look at this answer:
You can do the following:
dynamic myNewObject = JsonConvert.DeserializeObject(json); which will
return a dynamic object which you can work with.
Console.WriteLine(myNewObject.data[0].description); Obviously, it will
fail if your JSON doesn't contain data array having objects with
description property.
The whole question/answer: https://stackoverflow.com/a/34284972/5056173
Based on this, you can use NewtonSoft Json to get the properties.
Another way is to filter it by yourself:
var startIndex = json.IndexOf("vt1hourlyForecast")-1;
var filteredJson1 = json.Substring(startIndex, json.Length - startIndex);
var endIndex = filteredJson1.IndexOf("}]")+2;
var filteredJson2 = filteredJson1.Substring(0, endIndex);
var jsonValidFilteredJson = "{"+filteredJson2+"}";
var yourObject = JsonConvert.DeserializeObject<Vt1hourlyForecast>(jsonValidFilteredJson);
You can use this class:
public class Vt1hourlyForecast
{
public string processTime { get; set; }
public int temperature { get; set; }
public int precipPct { get; set; }
public string precipType { get; set; }
public int uvIndex { get; set; }
public int icon { get; set; }
public int iconExtended { get; set; }
public string windDirCompass { get; set; }
public int windDirDegrees { get; set; }
public int windSpeed { get; set; }
public string phrase { get; set; }
public string dayInd { get; set; }
public int severity { get; set; }
public int rh { get; set; }
public int feelsLike { get; set; }
}

Defining a dictionary in a C# class

I have a .json file which i want to read in C#.
The Json File looks like this:
{"SN0124":{
"category1": 0,
"output": {
"ABC": [],
"DEF": 0,
"GHI": "ABDEF"
},
"category2": 0,
"category3": 0
},
"SN0123":{
"category1": 0,
"output": {
"ABC": ["N1", "N2"],
"DEF": 0,
"GHI": "ABDEF"
},
"category2": 0,
"category3": 0
}
Initially the output field was absent and my custom class for reading the Json file is as follows:
namespace Server.Models
{
public class Pets
{
public string category1 { get; set; }
public string category2 { get; set; }
public string category3 { get; set; }
}
}
The output was recently added and I am not sure how to include that dictionary in the class file so that I can read the json file. Any help will be greatly appreciated.
thanks!
This should work fine. I have basically created a new class called Output that contains the expected JSON fields. I have also edited the type of the category fields to int.
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string JSONInput = #"{""SN0124"": {
""category1"": 0,
""output"": {
""ABC"": [],
""DEF"": 0,
""GHI"": ""ABDEF""
},
""category2"": 0,
""category3"": 0
},
""SN0123"": {
""category1"": 0,
""output"": {
""ABC"": [""N1"", ""N2""],
""DEF"": 0,
""GHI"": ""ABDEF""
},
""category2"": 0,
""category3"": 0
}}";
Dictionary<string, Pets> deserializedProduct = JsonConvert.DeserializeObject<Dictionary<string, Pets>>(JSONInput);
Console.ReadKey();
}
}
public class Output
{
public string[] ABC { get; set; }
public int DEF { get; set; }
public string GHI { get; set; }
}
public class Pets
{
public int category1 { get; set; }
public Output output { get; set; }
public int category2 { get; set; }
public int category3 { get; set; }
}
}
I'm not sure I fully understand what you mean. If I understand right you're trying to hold the values from output in a dictionary?
You could do something like:
var output = new Dictionary<string, string[]>();
But it might be simpler to create a custom class to hold that data structures.

Can't deserialize json

Can someone help me figure out how to deserialize this using json.net in C#? I have already successfully parsed a different json but its format was different. I've tried to use object and it says it needs to be an array and then I change it to array it says it needs to be an array..
Oh and there can be additional arrays with different "TYPE"..
"[
{
"ID": 1,
"TYPE": 1,
"APP_TAG": 1,
"alert": "[13:13] This is a Test Message - 0.",
"sound": "Default",
"badge": 0
}
]"
Since it is an array/list
public class Item
{
public int ID { get; set; }
public int TYPE { get; set; }
public int APP_TAG { get; set; }
public string alert { get; set; }
public string sound { get; set; }
public int badge { get; set; }
}
var items = JsonConvert.DeserializeObject<List<Item>>(json);
string json = #"[
{
'ID': 1,
'TYPE': 1,
'APP_TAG': 1,
'alert': '[13:13] This is a Test Message - 0.',
'sound': 'Default',
'badge': 0
}
]";
var items = Newtonsoft.Json.JsonConvert.DeserializeObject(json);

Categories

Resources