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);
Related
This is my first attempt of working with JSON deserialization. I have read many of the posts in Stackoverflow, non of the suggested solutions could match my issue, so my apology in advance. I have created the following objects:
public class Item
{
public int ID { get; set; }
public int LSum { get; set; }
public int YSum { get; set; }
public int TSum { get; set; }
public int NSum { get; set; }
public int MemberId { get; set; }
}
public class Something
{
public int Id { get; set; }
public string Phone { get; set; }
public bool ExistingMember { get; set; }
public IList<Item> Item { get; set; }
}
And when deserialize the JSON it looks like following:
The follwoing JSON what I expect it to be:
{
"Id":62,
"Phone":"07",
"ExistingMember":true,
"Item":[
{
"ID":42,
"LSum":0,
"YSum":0,
"TSum":0,
"NSum":0,
"MemberId":12
}
]
}
However the following method it
some= JsonConvert.DeserializeObject<something>(someResponse);
It prints the json like the following:
The following JSON is what is "someResponse" return,
{
"Id":62,
"Phone":"07",
"ExistingMember":true,
"Item":null
}
What am I missing that the item list is return null?
If you want to deserialize json string which in your case is someResponse variable, then you are doing it right.
To check your code I created a JSON file with a file.json name and put the following on it:
{
"Id": 62,
"Phone": "07",
"ExistingMember": true,
"Item": [
{
"ID": 42,
"LSum": 0,
"YSum": 0,
"TSum": 0,
"NSum": 0,
"MemberId": 12
}
]
}
Then below lines of code take the content of JSON file (which in your case is the content of someResponse) and deserialize it into c# object of Something type:
string jsonFilePath = #"C:\test\file.json";
var some = JsonConvert.DeserializeObject<Something>(File.ReadAllText(jsonFilePath));
Then print the ID property of each element of Item list:
foreach(var item in some.Item)
{
if (item != null)
{
Console.WriteLine($"item ID = {item.ID}");
}
}
The output:
item ID = 42
So, it is quite possible that someResponse just does not have an Item and looks like this:
{
"Id": 62,
"Phone": "07",
"ExistingMember": true
}
UPDATE:
Also I tried like this:
var someResponse = #"{
'Id': 62,
'Phone': '07',
'ExistingMember': true,
'Item':[
{
'ID': 42,
'LSum': 0,
'YSum': 0,
'TSum': 0,
'NSum': 0,
'MemberId': 12
}
]
}
";
var some = JsonConvert.DeserializeObject<Something>(someResponse);
And some has a Item list with 1 element
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
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; }
}
Can someone tell me how to deserialize JSON to a C# (without using C# dynamic) object when JSON string is having dynamic array of data?
Given below JSON is having Boxes object and it can contain Array of fashion items (It can be pants, sweater, shoes,...etc)
{
"task": {
"id": 269740275,
"status": "success",
"error": null,
"date_created": "2017-02-16T10:33:41.827688Z",
"date_updated": "2017-02-16T10:33:42.417778Z",
"data": {
"width": 1062,
"boxes": {
"top-shirt": [
{
"xmin": 0.249980241060257,
"ymin": 0.1535395532846451,
"ymax": 0.476559966802597,
"xmax": 0.6146213412284851,
"proba": 0.9977585077285767
}
],
"shoe": [
{
"xmin": 0.3686676025390625,
"ymin": 0.9223044514656067,
"ymax": 0.9838011264801025,
"xmax": 0.4768480360507965,
"proba": 0.9748706817626953
}
],
"pants": [
{
"xmin": 0.3451904654502869,
"ymin": 0.4616038501262665,
"ymax": 0.909162700176239,
"xmax": 0.6047541499137878,
"proba": 0.9983627200126648
}
]
},
"height": 1503
}
}
}
You can use a dictionary to handle the dynamic part of the JSON (boxes).
Define your classes like this:
public class RootObject
{
public Task task { get; set; }
}
public class Task
{
public int id { get; set; }
public string status { get; set; }
public object error { get; set; }
public DateTime date_created { get; set; }
public DateTime date_updated { get; set; }
public Data data { get; set; }
}
public class Data
{
public int width { get; set; }
public Dictionary<string, List<Item>> boxes { get; set; }
public int height { get; set; }
}
public class Item
{
public double xmin { get; set; }
public double ymin { get; set; }
public double ymax { get; set; }
public double xmax { get; set; }
public double proba { get; set; }
}
Then deserialize like this:
RootObject obj = JsonConvert.DeserializeObject<RootObject>(json);
Fiddle: https://dotnetfiddle.net/Sxz8P3
Use NuGet to fetch the Newtonsoft.JSON package.
Then you can use linq-to-json to handle this kind of data object.
For example, assuming your example JSON string is stored in input,
var message = JObject.Parse(input);
var width = (int)message["task"]["data"]["width"];
var height = (int)message["task"]["data"]["height"];
Console.WriteLine(width + " " + height);
var boxes = message["task"]["data"]["boxes"];
foreach (var box in boxes.Children<JProperty>())
{
Console.WriteLine(box.Name) ;
}
This is pretty close to Javascript and works well.
I think O. Jones provided the easiest solution, using Newtonsoft, Newtonsoft is literally the best possible way to do anything with JSON in C# and without any headaches.
Here's one of the simplest examples
string json_string = #"{
Firstname: ""Jane"",
Lastname: ""Doe"",
Age: 36,
IsEmployed: true,
IsMarried: true,
Children: 4
}";
var person = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(json_string);
Console.WriteLine(person.Forename);
Console.WriteLine(person.Lastname);
Console.WriteLine(person.Age);
Console.WriteLine(person.IsEmployed);
Console.WriteLine(person.IsMarried);
Console.WriteLine(person.Children);
It generates objects on the fly, no matter the structure!
I wrote a simple, easy-to-follow article here https://turmanauli.medium.com/a-complete-guide-for-serializing-json-to-dynamic-objects-on-the-fly-in-c-7ab4799f648d
about how to use Newtonsoft in your Visual Studio project.
I have this callback
{
"status": "200",
"name": "Something Here",
"serverversion": "v1.2.4.1",
"tshockversion": {
"Major": 4,
"Minor": 2,
"Build": 4,
"Revision": 128,
"MajorRevision": 0,
"MinorRevision": 128
},
"port": 7777,
"playercount": 27,
"maxplayers": 60,
"world": "Something Here",
"uptime": "0.05:14:08",
"serverpassword": false
}
Windows Form Application, so i need to write on label1 like this: 27 from 60.
Help me, please.
So you want to parse a json response and display the text playercount + " from " + maxplayers on a label. yes?
First you need a strongly typed class. Use a tool like json2sharp to define the class and save it to your project.
public class Tshockversion
{
public int Major { get; set; }
public int Minor { get; set; }
public int Build { get; set; }
public int Revision { get; set; }
public int MajorRevision { get; set; }
public int MinorRevision { get; set; }
}
public class JsonResponse
{
public string status { get; set; }
public string name { get; set; }
public string serverversion { get; set; }
public Tshockversion tshockversion { get; set; }
public int port { get; set; }
public int playercount { get; set; }
public int maxplayers { get; set; }
public string world { get; set; }
public string uptime { get; set; }
public bool serverpassword { get; set; }
}
then, you can convert the json string and update your label
JsonResponse data = JsonConvert.DeserializeObject<JsonResponse>(json);
label1.Content = data.playercount + " from " + data.maxplayers
Why do you not simply follow the manual?
http://www.newtonsoft.com/json/help/html/SerializingJSON.htm
You may create a class, deserialize it and then you can access the properties of the deserialized object from the response you've got.
Assuming that json_response is a string containing the text from OP ...
string json_response = {
"status": "200",
"name": "Something Here",
"serverversion": "v1.2.4.1",
"tshockversion": {
"Major": 4,
"Minor": 2,
"Build": 4,
"Revision": 128,
"MajorRevision": 0,
"MinorRevision": 128
},
"port": 7777,
"playercount": 27,
"maxplayers": 60,
"world": "Something Here",
"uptime": "0.05:14:08",
"serverpassword": false
}
... then using Newtonsoft.Json.Linq JToken.Parse() Method which lets you parse either JObject or JArray objects ...
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
... you can try this ...
JObject data = (JObject)JToken.Parse(json_response);
label1.Content = data["playercount"].ToString() + " from " +
data["maxplayers"].ToString();
References
Json.NET
Json.NET Documentation
LINQ to JSON
Parsing JSON
Querying JSON with LINQ
JToken.Item Property
Newtonsoft.Json.Linq Namespace
Have you tried:
....
"uptime": "0.05:14:08",
"serverpassword": false,
"label1" : function(){return playercount + ' from ' + maxplayers;}
}
Is that what you wanted?