C# - Deserialize JSON(.net) to ListBox - c#

I'm currently working on a project which requires me to deserialize a JSON file, but it's showing to be harder to do and understand than I initially thought it would be.
What I want to do is deserialize this JSON file into a ListBox on my Windows Form project (located here). I want to put each of the versions located in "Unity5Stable" into the ListBox (5.4.3, 5.4.2, etc.)
Partial json:
{
"Unity5Stable": {
"5.4.3": {
"x86": "http://netstorage.unity3d.com/unity/01f4c123905a/Windows32EditorInstaller/UnitySetup32-5.4.3f1.exe",
"x64": "http://netstorage.unity3d.com/unity/01f4c123905a/Windows64EditorInstaller/UnitySetup64-5.4.3f1.exe"
},
"5.4.2": {
"x86": "http://download.unity3d.com/download_unity/b7e030c65c9b/Windows32EditorInstaller/UnitySetup32-5.4.2f2.exe",
"x64": "http://download.unity3d.com/download_unity/b7e030c65c9b/Windows64EditorInstaller/UnitySetup64-5.4.2f2.exe"
},
"5.4.1": {
"x86": "http://download.unity3d.com/download_unity/649f48bbbf0f/Windows32EditorInstaller/UnitySetup32-5.4.1f1.exe",
"x64": "http://download.unity3d.com/download_unity/649f48bbbf0f/Windows64EditorInstaller/UnitySetup64-5.4.1f1.exe"
}
}
}
I've tried a few different suggestions from a couple sites but I'm having a hard time finding anything related to putting the objects into a ListBox.
Any help would be greatly appreciated!

Im not familiar with listboxes but I do know you can deserialize a json into an object. You create an object with the same type and name variables your json has, deserialize into it and then you can access your variables. I used newtonsoft.JSON in a xamarin forms project.

JSON Deserialization
You can deserialize JSON to an known type with the JsonSerializer from Newtonsoft.Json (More details here)
Or with the Json class from System.Web.Helpers you can deserialize JSON to an dynamic. (More details here)
dynamic data = Json.Decode(json);
ListBox
Your ListBox has an property Items which is an collection where you can add objects. You can add a string or any other object. The ToString method of the object will be called and it's value will be displayed.

Related

Cannot deserialize type without setter

I have binary serialized objects in database. They are serialized with protobuf.
Now I need to generate some viewer to see the content of Database.
So, i read stream from database and deserialized it back to the objects.
It works and the result is list of objects:
var dbData = readData(someType);//it is IList collection
Now, I would like to save this list of objects to file to see the content of database. I thought it would be the best to save it to xml. So, i have tried:
var serializer = new XmlSerializer(dbData.GetType());
But i get an error: Cannot deserialize type 'My.Entities.IdBase' because it contains property 'Key' which has no public setter.
What now? I can't change the class definitions to have setters.
Should i save objects to json or plain text instead? Or should i extract all properties and values and save it to some xml? Any code example?
JSON.NET would be the answer here. You can find it in nuget. Use it like this:
JsonConvert.DeserializeObject<T>(input);

How to parse a collection of unknown JSON object types inside a known JSON structure using JSON.Net?

I am attempting to parse some JSON that has a known top level schema. However inside the schema is one JSON object that can contain various types of JSON objects.
Example
{
"knownfield1": data,
"knownfield2": data,
"knownfieldcollection":
{
"fieldofunknowntype1": "string data",
"fieldofunknowntype2":
{
"subunknownfield1": "string data",
"subunknownfield1": null
},
"fieldofunknowntype3": null
}
}
I would like to make an object that contains a mapping of the known fields, but can read the unknown fields in dynamically. I was trying with Json.Net JToken and JObject, but I could not get it to work. I kept getting recursive JToken exceptions.
Any pointers on this would be great. Thank you.
Exception I am getting:
Type 'Newtonsoft.Json.Linq.JToken' is a recursive collection data
contract which is not supported. Consider modifying the definition of
collection 'Newtonsoft.Json.Linq.JToken' to remove references to itself.
--edit--
Mistyped Collection for object, fixed that.
We have a winner. DBC hit the nail on the head. I had some left over WFC deserialization and it was causing problems. As soon I made sure all the DataContract code was completely cleared out and replaced everything with proper JSON.Net tags and calls, it worked wonderfully.
Thank you everyone for the support.

C# dynamic JSON serialization

I'm calling an API to fetch a list of devices. In my model i have an attribute for list of devices:
public List<Device> device { get; set; }
But, if the API returns 1 device, it's returned as just a Device, not a list of devices with 1 device.
Is there any good way to have a dynamic deserialize? I don't want to have two different models, and parse the JSON programatically just to know which object to deserialize as.
JsonConvert.DeserializeObject<ListDevicesByLabelModel>(responseText);
The dynamic keyword is still great for deserializing JSON, I would recommend that you take a look on this question.
Deserialize JSON into C# dynamic object?
dynamic data = Json.Decode(responseText);
And then you've got a dynamic object to work with instead of needing 2 models.
Otherwise you could also have just one item in the List.

How to explicitly call the ASP.NET json serializer

So I have a small asp.net app which returns Json objects that are serialized from C# objects. If I just create a function:
[HttpGet(getTheObj)]
public SomeObj GetTheObject()
{
return new SomeObj() { SomeProperty = 1 };
}
Then it works fine and I can do an HttpRequest for the Json object. However I also want to save some these serialized objects into a database for later use. So I'm wondering, can I explicitly call the Json serializer? I understand that several different serializers can be used with ASP.NET, how do I figure out which one I am using (I didn't create the project).
string json = JsonConvert.SerializeObject(_data.ToArray());
you can save this in database. you can again retrive this object from database and deserialize this object.

Serialize whole instance with child instances (class serialization) and save to file

I'm building a game with Unity3D. I have a class called GameInstance containing all the current game instance data in it. It contains multiple sub classes for instance the Player property would return a Player object.
Yet all objects are simple key/values objects, it's only data. Now I'd need to serialize all of this and save it to a file so I can reload it to restart the game where it left.
That's what I basically intent to do, maybe somebody would have a better suggestion but yet that's the most flexible option I found.
I used .NET XML object serialization in the past but it's been a while and I'd need to have a more direct advice on this. Should I serialize to XML or JSON for example?
TL;DR: I want to serialize a whole class with all its content with C#/.NET in a Unity3D project. How should I proceed?
Thanks!
I personally prefer json. If you're using json.NET this will be as simple as;
string json = JsonConvert.SerializeObject(MyObject);
or to compact it;
File.WriteAllText("./myfile", JsonConvert.SerializeObject(MyObject));
Then to deserialize you would just do;
MyObject obj = JsonConvert.DeserializeObject<MyObject>(File.ReadAllText("./myfile"));
EDIT: In response to the exception, you want to use this overload which allows you to change the serilization settings;
JsonConvert.SerializeObject(ResultGroups,
new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});

Categories

Resources