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?
Related
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();
}
}
}
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
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.
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);