C# dynamic JSON serialization - c#

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.

Related

C# - Deserialize JSON(.net) to ListBox

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.

How would I deserialize a json array that contains pairs without keys?

Let's say I have some json similar to the following:
"productdetails": [["loading"], ["loaded"], ["detailkey", "detailvalue"]]
The formatting is out of my control, and I need to be able to access the 'loading' and 'loaded' parts to make sure the data was loaded properly before moving on further to continue work with the data. I haven't been able to figure out how to setup nested properties that also have no key.
Edit: Should have noted, 'loading' and 'loaded' can be different things and there can be varying amounts of status update arrays before the details or other messages. So, the above could be returned, or something like this:
"productdetails": [["loading"],["empty"],["created"],["loaded"],["detailkey", "detailvalue"]]
Edit 2: Excuse the errors in my json syntax, the colons have been switched out to create a properly syntaxed example.
This is just a two-dimensional array, which can be represented as a list of list of string
You should be able to deserialize it to this object:
public class RootObject
{
public List<List<string>> productdetails { get; set; }
}
I recomment Newtonsoft's Json.Net parser.
Example:
string jsonString = "{\"productdetails\": [[\"loading\"], [\"loaded\"], [\"detailkey\", \"detailvalue\"]]}";
RootObject obj = JsonConvert.Deserialize<RootObject>(jsonString);

How to index in Elastic Search a typed object with a GeoShape string GeoJson polygon?

I have a typed class that contains a GeoJson string variable that represents a polygon.
How can I index it in Elastic Search using NEST?
Marking the field with:
[ElasticProperty(Type = FieldType.GeoShape)]
public string Polygon { get; set; }
and having it in the CreateIndex as
.GeoShape(s => s
.Name(m => m.Polygon)
.Tree(GeoTree.Geohash)
.TreeLevels(2)
.DistanceErrorPercentage(0.025))
Gives this error:
failed to parse [polygon]]; nested: ElasticsearchParseException[Shape must be an object consisting of type and coordinates"
Since I have the GeJSon as the input and the GeoShape has the coordinates as Geo JSON, how can I map this data? I could deserialize the input and populate the ES structure, but it seems like a too complicated, error prone approach.
Thank you,
Monica
I wrote a blog post about working with Geospatial queries with Elasticsearch and NEST.
A good way of handling fields that you want to persist as geo_shape types and work with them easily within your application is to use NetTopologySuite that contains,amongst many other useful things, a serializer to convert IGeometry types (e.g. Polygon, LineString, MultiPolygon) in code into GeoJSON, the format that the geo_shape type supports. The serializer can then be registered with the NEST client so that model properties of type IGeometry are handled correctly.
I have an example of doing this up on BitBucket.
Russ Cam's solution looks nice. But it's overkill if you need just get shapes from a file and import it into ElasticSearch. To make it work you just need to deserialize your json to an object.
JsonConvert.DeserializeObject<object>(json);
So if model has Polygon as object instead of string, it will work.
[ElasticProperty(Type = FieldType.GeoShape)]
public object Polygon { get; set; }

Dynamically Rendering a JSON String to a Table in C#

I need help mapping a complex C# object to a table dynamically, without manually defining a model. I'm using ASP.NET 4.5.
So I am using JSON.NET to serialize my complex C# object into a JSON object with
string json = JsonConvert.SerializeObject(myObject, Formatting.Indented);
This object is being read in dynamically from an external API. It includes complex attributes, like dictionaries, as well as standard strings, integers, etc. I input in a key and it returns the C# object.
I can't manually map the object to a model, since the object does change frequently with development, and needs to be extensible despite changes in the C# object. What is the best way to map this JSON object to a table? Essentially need to be able to render the JSON serialized from the object into a readable table with ASP.NET.
Thanks so much!

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.

Categories

Resources