C# Json Deserialization - c#

I have been asked to work with json data in order to create a quiz game in windows phone. I knew that I had to use json.net to achive this which I have previously used in the past but the method I used in the past is no useful here.
My question is this. I have this json string
[{"corr":"1","q":"text.","type":"0"},
{"corr":"0","q":"text.","type":"0"},
{"corr":"1","q":"text.","type":"0"},
{"corr":"0","q":"text.","type":"0"},
{"corr":"0","q":"text.","type":"0"},
{"corr":"1","q":"text.","type":"0"},
{"corr":"4","q":"text","a":["text","text","text","text"],"type":"1"},
{"corr":"2","q":"text","a":["text","text","text","text"],"type":"1"},
{"corr":"1","q":"text","a":["text","text","text","text"],"type":"1"},
{"corr":"2","q":"text","a":["22,2%","45%","54%","67%"],"type":"1"}]
and as you can image I want to fill some List with the properties above.
I have created the following class in order to represent the json objects
public class QuizObj
{
public string corr { get; set; }
public string q { get; set; }
public string type { get; set; }
public List<string> a { get; set; }
}
but I don't really know how to use it and can't find something really relevant.

Something like this should do the trick:
var quizObjs = JsonConvert.DeserializeObject<List<QuizObj>>(serializedStringValue);
string corr = quizObjs.First().corr;
// or
foreach(var quizObj in quizObjs)
{
string corr = quizObj.corr;
// etc
}
You will need to add a reference to NewtonSoft.Json, which you can get via NuGet (if you haven't already).

Related

Deserialize JSON to C# Objects with Childs

I have a JSON string and I need some help to deserialize it.
At the moment my result is always null.
var results = JsonConvert.DeserializeObject<Root>(json);
// result == null
My JSON:
{"First":{"FirstData1":{"date":"2018-01-01","hint":""},
"FirstData2":{"date":"2018-01-06","hint":""}},
"Second":{"SecondData1":{"date":"2018-01-01","hint":""},
"SecondData2":{"date":"2018-01-06","hint":""}}}....
Only on the last Node there is actual property naming...
MyObjects
public class Root
{
public IEnumerable<TempModelRoot> Value{ get; set; }
}
public class TempModelRoot
{
[JsonProperty("Key")]
public string Key { get; set; }
[JsonProperty("Value")]
public List<TempModelChild> Value { get; set; }
}
public class TempModelChild
{
[JsonProperty("Key")]
public string Key { get; set; }
[JsonProperty("Value")]
public TempModelInfo Value { get; set; }
}
public class TempModelInfo
{
[JsonProperty("date")]
public string date { get; set; }
[JsonProperty("hint")]
public string hint { get; set; }
}
In addition to #MX D 's answer, I want to add two more useful model generator sites, which takes JSON as an input and gives appropriate model classes.
Json2Csahrp
JsonUtils
Use, whenever you find difficult to generate complex model classes.
Most likely you are having a mismatch between the model you are trying to deserialize to, and the actual expected model based of the json itself.
A easy way to resolve this is by using a tool such as Quick Types Model Generator(unafiliated) which allows you to generate C# models based upon a provided json file.
After generation you can compare and/or replace your models with the generated models.
To spot and resolve the issue with your model.

Converting a string to JSON in C#

I'm trying to use Simple JSON to convert this string to JSON :
"{\"objects\":[{\"id\":1,\"title\":\"Book\",\"position_x\":0,\"position_y\":0,\"position_z\":0,\"rotation_x\":0,\"rotation_y\":0,\"rotation_z\":0,\"created\":\"2016-09-21T14:22:22.817Z\"},{\"id\":2,\"title\":\"Apple\",\"position_x\":0,\"position_y\":0,\"position_z\":0,\"rotation_x\":0,\"rotation_y\":0,\"rotation_z\":0,\"created\":\"2016-09-21T14:22:52.368Z\"}]}"
Unfortunately, it appears that Visual Studio doesn't have Interactive Debugging Console. As in, placing a debugger on a line, and stepping into that part of the code in a live interactive console. Where I would otherwise be able to experiment with SimpleJSON's library and see how to make this work. By all means, correct me if I'm wrong!
Being that that's impossible though, would anyone know how to accomplish this? I have tried this :
JSONData jsonData = new JSONData(my_json_string);
But that escapes the string even more and keeps it a string :
"\"{\\\"objects\\\":[{\\\"id\\\":1,\\\"title\\\":\\\"Book\\\",\\\"position_x\\\":0,\\\"position_y\\\":0,\\\"position_z\\\":0,\\\"rotation_x\\\":0,\\\"rotation_y\\\":0,\\\"rotation_z\\\":0,\\\"created\\\":\\\"2016-09-21T14:22:22.817Z\\\...
I'm new to C#, but I'm surprised there's nothing native to C# that would make something as common as parsing JSON more accessible. Is there one?
The question asks how to convert a string to a JSON object... This can be achieved without using a Class or data model, as follows:
using Newtonsoft.Json;
string str = "{\"objects\":[{\"id\":1,\"title\":\"Book\",\"position_x\":0,\"position_y\":0,\"position_z\":0,\"rotation_x\":0,\"rotation_y\":0,\"rotation_z\":0,\"created\":\"2016-09-21T14:22:22.817Z\"},{\"id\":2,\"title\":\"Apple\",\"position_x\":0,\"position_y\":0,\"position_z\":0,\"rotation_x\":0,\"rotation_y\":0,\"rotation_z\":0,\"created\":\"2016-09-21T14:22:52.368Z\"}]}";
dynamic json = JsonConvert.DeserializeObject(str);
Now, you can access the json contents as follows:
json["objects"][0]["title"];
returns "Book"
One option for an "Interactive Debugging Console" where you can play around with C# code is Xamarin Workbooks...
microsoft.com/en-us/xamarin/tools/workbooks/
Xamarin Workbooks provide a blend of documentation and code that is perfect for experimentation, learning, and creating... blah blah blah
First, create your data model. You can use json2sharp, very helpful tool.
public class Item
{
public int id { get; set; }
public string title { get; set; }
public int position_x { get; set; }
public int position_y { get; set; }
public int position_z { get; set; }
public int rotation_x { get; set; }
public int rotation_y { get; set; }
public int rotation_z { get; set; }
public string created { get; set; }
}
Next use Newtonsoft.Json and call deserialize method.
var list = JsonConvert.DeserializeObject<List<Item>>(Yourjson);
Did you try system utilities?
Like this one https://msdn.microsoft.com/ru-ru/library/system.json.jsonvalue.parse%28v=vs.95%29.aspx
You can use
public static JsonValue Parse(string jsonString)
from JsonValue class and cast then to jsonobject or anything you want.

Modify a JSON string

I have a string in JSON format as follows
string jsonStr = "{"Type":1, "Id":1000,"Date":null,"Group": "Admin","Country":"India","Type":1}";
I want to modify this string so that Id attribute should always be the first. The order of attributes matters.
Is there any way I can modify this string.
I tried searching google but did not find appropriate solution.
Any help would be appreciated.
EDIT:
I also tried to deserialize object using
object yourOjbect = new JavaScriptSerializer().DeserializeObject(jsonStr);
But here also the "type" attribute comes first. I dont find any way to move the attributes within this deserialized object
It's possible. Use the JsonProperty attribute, property Order.
http://www.newtonsoft.com/json/help/html/JsonPropertyOrder.htm.
Let me know if it works.
Instead of attempting to manipulate the order of the outputted JSON and comparing strings, I would transform both JSON strings that you want to compare, into objects and then perform your comparison. You could then compare individual properties or entire objects with something like the following:
void CompareJSON()
{
string json = #"{""Type"":1, ""Id"":1000,""Date"":null,""Group"": ""Admin"",""Country"":""India"",""Type"":1}";
string jsonToCompare = "JSON TO COMPARE";
MyObject myJsonObject = JsonConvert.DeserializeObject<MyObject>(json);
MyObject myJsonObjectToCompare = JsonConvert.DeserializeObject<MyObject>(jsonToCompare);
if (myJsonObject.Id == myJsonObjectToCompare.Id)
{
// Do something
}
}
class MyObject
{
public int Id { get; set; }
public int Type { get; set; }
public DateTime? Date { get; set; }
public string Group { get; set; }
public string Country { get; set; }
}
Please note that this example is carried out using the Newtonsoft.JSON library. More information on the library can be found here.
Just make your JSON into a c# class with Id first and then serialize it again if that is what you need. You do know that you have "Type" twice in the JSON string? In this solution it will get "fixed" so you only have it once as it should be. But if your string really is with two Type this wont work since the strings will be incorrect. If they really are like that you need to do some ugly string manipulation to fix the order but i hope the first string is incorrect only here and not in your code.
private void Test() {
string json = #"{""Type"":1, ""Id"":1000,""Date"":null,""Group"": ""Admin"",""Country"":""India"",""Type"":1}";
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
MyJsonObject myJsonObject = jsonSerializer.Deserialize<MyJsonObject>(json);
string s = jsonSerializer.Serialize(myJsonObject);
//Returns: {"Id":1000,"Type":1,"Date":null,"Group":"Admin","Country":"India"}
}
class MyJsonObject {
public int Id { get; set; }
public int Type { get; set; }
public DateTime? Date { get; set; }
public string Group { get; set; }
public string Country { get; set; }
}

JsonValue.Parse not returning correct results

I am trying to parse a .Json file which can be found here - http://files.star-made.org/releasebuildindex.json with this snippet I found on this site -
WebClient webClient = new WebClient();
dynamic result = JsonValue.Parse(new WebClient().DownloadString("http://files.star-made.org/releasebuildindex.json"));
Console.WriteLine(result.builds.version);
With the current version of the file (changes every week or 2 with a game update), it should be returning the string "0.163", yet it currently returns "default", which after some messing around, is what it returns if that tag does not actually exist.
I have no knowledge of Json, and can not edit that file as I am not its creator, any assistance is greatly appreciated.
-James
Builds is an array. You get the version like this:
Console.WriteLine(results.builds[0].version);
To explore the structure of a json string you can use http://json2csharp.com/.
Dynamic keyword is nice, but it is way better to have static code checking and auto-complete. To enable this you need to have POCO(Plain Old CLR(Common Language Runtime) Object).
Copy Json and Paste special -> Paste as json classes (you need at least Visual studio 2012.2 RC):
public class Rootobject
{
public string indexfileversion { get; set; }
public string type { get; set; }
public Build[] builds { get; set; }
}
public class Build
{
public string version { get; set; }
public string build { get; set; }
public string rawVersion { get; set; }
public string path { get; set; }
}
Then you can use :
var json = new WebClient()
.DownloadString("http://files.star-made.org/releasebuildindex.json");
var result = new JavaScriptSerializer().Deserialize<Rootobject>(json);
Console.WriteLine(result.builds[0].version);

How to map JSON to C# Objects

I am having issues with understanding how to make this happen.
Basically we have an API, the user sends a JSON of the format:
{
"Profile":[
{
"Name":"Joe",
"Last":"Doe",
"Client":{
"ClientId":"1",
"Product":"Apple",
"Message":"Peter likes apples"
},
"Date":"2012-02-14"
}
]
}
I have a class called Profile with parameters Name, Last, and an object as one of its members called Client as well as property Date.
Something like this:
public class Profile {
public string Name {get; set;}
public string Last {get; set;}
public Client client {get; set;}
public DateTime dDate {get; set;}
}
So basically, I am not sure how to grab the JSON and then map it to my object.
Any help with "helping" me understand would be much appreciated.
You can use Json.NET to deserialize your json string as (with some modifications to your classes)
var yourObject = JsonConvert.DeserializeObject<Root>(jsonstring);
public class Root
{
public Profile[] Profile;
}
public class Profile
{
public string Name { get; set; }
public string Last { get; set; }
public Client Client { get; set; }
public DateTime Date { get; set; }
}
public class Client
{
public int ClientId;
public string Product;
public string Message;
}
You can use a JSON library for this, for example Newtonsoft.Json which is free. It will map json to your types automatically.
Sample:
public static T Deserialize<T>(string json)
{
Newtonsoft.Json.JsonSerializer s = new JsonSerializer();
return s.Deserialize<T>(new JsonTextReader(new StringReader(json)));
}
There is also a NuGet package available.
Easiest way I know is to use JSON.Net by newtonsoft.
To make it easier to understand, I always make matching classes in C# with the same name.
Then its easier to deserialize it.
As an example, if it is an array of objects in js, it will map to a list of object with the same names in C#.
As for the date time, its a bit tricky.
Id do the client side validation and Datetime.tryParse in the serverside, itll take care of the dashes or slashes.
var serializer = new JavaScriptSerializer();
List<abc> abcList = serializer.Deserialize<List<abc>>(PassedInJsonString);
I know this is a long time question, but I would like to add one more option, which does not use third party libraries, and only uses stock .Net libraries, and is available from .Net Core 3.1 onwards.
First of all, I leave a link to the official Microsoft documentation (where you will find examples on how to serialize and deserialize json strings): https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to
Let's build on your example. We have our starting json string:
{
"Profile":[
{
"Name":"Joe",
"Last":"Doe",
"Client":{
"ClientId":"1",
"Product":"Apple",
"Message":"Peter likes apples"
},
"Date":"2012-02-14"
}
]
}
If we build a data structure that can hold that definition, it would be something like:
public class Root
{
public List<Profile> Profile { get; set; }
}
public class Profile
{
public string Name { get; set; }
public string Last { get; set; }
public Client Client { get; set; }
public string Date { get; set; }
}
public class Client
{
public string ClientId { get; set; }
public string Product { get; set; }
public string Message { get; set; }
}
Now, and finally the answer to how to deserialize a json string into a particular object without third party libraries:
Root root = JsonSerializer.Deserialize<Root>(json);
Where json is the variable that contains your json string.
I add another link of interest, the official documentation of the Deserialize(...) method: https://learn.microsoft.com/en-us/dotnet/api/system.text.json.jsonserializer.deserialize
Something that is really useful is the exception that can be thrown, JsonException: https://learn.microsoft.com/en-us/dotnet/api/system.text.json.jsonexception
DataContractJsonSerializer does the job, but it uses more sophisticated format for DateTime serialization.

Categories

Resources