Deserialize JSON array of mixed content - c#

Apolgies: I forget to mention this is for a Silverlight Solution.
A JSON string is returned from a service as:
{
"710 HUVAL ST (N), LAFAYETTE LA":{
"confidence":0.844,
"fips_county":"22055",
"country_code":"US",
"country_code3":"USA",
"latitude":30.234912,
"street_address":"710 Huval St",
"country_name":"United States",
"longitude":-92.034597,
"street_number":"710",
"region":"LA",
"street_name":"Huval St",
"locality":"Lafayette"
},
"200 ASHLAND PARK, LAFAYETTE LA":{
"confidence":0.844,
"fips_county":"22055",
"country_code":"US",
"country_code3":"USA",
"latitude":30.159882,
"street_address":"200 Ashland Park Dr",
"country_name":"United States",
"longitude":-92.035342,
"street_number":"200",
"region":"LA",
"street_name":"Ashland Park Dr",
"locality":"Lafayette"
}
}
I'm trying to deserialize it into a .NET class. However, I'm running into trouble because each object in the array (and it may be very large, I'm just showing two in the example above) looks to be a different object type to the JSON deserializer in .NET.
Using a tool like JSON to C# to generate the classes will create a class for each of the array objects, which is not ideal given that the results vary from response to response.
I cannot for the life of me figure out the appropriate class(es) to generate in .NET in order to be able to deserialize it. I don't have any control of the JSON service and I am stuck.

Try using the JSON.NET package from nuget. The class Newtonsoft.Json.Linq.JObject will give you an interface similar to System.Xml.Linq.XElement that will allow you to parse the JSON without having to deserialize it into a single concrete object.

Related

How to handle bunch of json objects with different names

the problem is that i dont know how to create model for json from api.
I used some online json to c# generator but it creates a very high count of classes what is unnecessary and very problematic with time.
thats my json:
https://solomid-resources.s3.amazonaws.com/blitz/tft/data/items.json
Fixed with this model
https://pastebin.com/SpGe72P7
and this serialization line
Dictionary<string, TftItems> foo = Drzewo.Configuration.DeserializeJson<Dictionary<string, TftItems>>(data);
where Configuration.DeserializeJson is just generic function of
JsonConvert.DeserializeObject<T>(json)

How to deserialize json and not make multiple instance of the class, in unity 3d and simplejson?

I am trying to parse a json or deserialize a json of the following format. Because of brain fart or not--I cant seem to get it to deserialize--basically I would create a class object with the json structure. Now I want to keep updating this object with new data from next json I receive from server call and now I don't want to create a new object every time...how do I do it? What am I missing?
I am doing this in C# (new to it) and Unity 3D, not using any serialization lib, just simplejson and JsonUtility (yes I know it sucks). I have complex inner structure.
{
JsonArray[5] -> more jsonArray inside
JsonArray[5]
JsonArray[5]
JsonArray[5]
JsonArray[5]
}
SimpleJson hasn't this feature, you need write your own implemention.
JsonUtility has one, use JsonUtility.FromJsonOverwrite

Json Operation Serialization

I'm trying to create a Json Parser for C# for use with Unity. Currently I'm using Json.net as the serializer and I'm having a bit of trouble. Essentially, in order to deserialize into a function, I'm using an Enum as a representation of a function pointer. the underlying code is working fine, but I'm having trouble getting the enum to map.
Essentially the object that would be created from the JSON string
"{'==': [1, 1]}"
would be
new Tuple<Enum, dynamic[]>(Enum.Equals, {1, 1})
and vice versa.
I have found this resource, but I don't think it goes quite far enough in its explanation: https://bytefish.de/blog/enums_json_net/
Essentially how do I set up Item 1 of the Tuple to be the name of Array Item 2?
One way to see JSON is as a combination of HashMaps (dictionaries), arrays and values.
When you parse a JSON into an object, that object is a combination of dictionaries, arrays, and values.
One way to represent an enum in JSON could be as follow:
{
"type": "string",
"enum: ["red", "blue", "yellow"]
}
So, perhaps you wish to extend the functionality of the library you are using to work with Tuples.
If I am not clear, please let me know.

Retrieve Dynamic class name from JSON.NET?

I'm receiving messages over a network using JSON.NET. The message format is somewhat dynamic, in that the messages will be represented by many different classes, each inheriting from a parent message. For example:
{
MessageName: "MessageType1",
Data1: 124,
Data2: "Something"
}
{
MessageName: "MessageType2",
OtherData: "Some data",
MoreData: "Even more",
ANumber: 25
}
The problem I'm having is that in JSON.NET, I have no idea how to figure out the name of the class (MessageType1/MessageType2/etc) in order to deserialize it into an instance of the class without deserializing it twice. There's a few options I've considered; the one I'm currently using is to use a container class containing the message name and the actual json message serialized to string, but this seems wasteful.
Another method I've considered is deserializing into a string/string dictionary and then performing the population of the class on my own, which seems messy and unnecessary considering JSON.NET can do that for me... as long as I know the class first.
I'm really hoping there's an easy way to have JSON.NET figure out a class name by examining the MessageName property and then continue to populate a class after examining that one property.
Thanks for the help!
JSON can deserialize into a well known class only. You need to specify the data layout (i.e. the class/type)
There are two alternatives:
1.) go one level deeper. Use the JSON Token parser to read the tokens from your JSON stream and act based on the tokens you find.
2.) as you suggested: Use a class layout flexible enough to hold all your possible variations like a key/value dictionary.

Is there a way to pass a list of JSON objects from JS to C#?

Something I'm confusing.
The Javascript is going to produce the following JSON data.
{type:"book" , author: "Lian", Publisher: "ABC"}
{type:"Newspaper", author: "Noke"}
This is only an example, actually I've got more than this.
Since I have common fields between different JSON data, so I don't know is it possible to pass this to C# at one time.
What I want to do is pass this to c# then do some processing, what is the best way to do? I'm using ASP.NET MVC2.
Thanks for your answer or hints.
The combination of the 2 JSON statements above are, together, not valid JSON. That being said, you will not be able to use the JavaScriptSerializer class to deserialize that data into c# structure directly. Instead you will have to do some manual parsing first, to either break it down into valid JSON or just do full on manual parsing.
What I would actually recommend is sending over valid JSON instead. You can accomplish this by doing something like this:
{list: [
{type:"book" , author: "Lian", Publisher: "ABC"},
{type:"Newspaper", author: "Noke"} ]
Hard to say exactly, since only you know the details of your use case. You can send this data over using a traditional 'ajax' request. This is very easy to do with out any of the many JS libraries out there, but I would recommend just going with one anyway - they offer higher level constructs that are easier to use (and address cross-browser idiosyncrasies).
Since you are using ASP.NET MVC2, I would recommend jQuery. Microsoft is now backing jQuery as their JS library of choice and even make it default for new web projects.
Once you pass the above JSON to C#, you can deserialize it by doing something like this:
JavaScriptSerializer serializer = new JavaScriptSerializer();
var result = serialzer.Deserialize<Dictionary<string, object>>(postedJSONData);
Your result will then have a structure that looks like this, in C#:
Dictionary<string, object> result =>
{ "list" => object },
object => List<object>,
List<object> => Dictionary<string, object>
{ "type" => "book", "author" => "Lian" } // etc
[
{type:"book" , author: "Lian", Publisher: "ABC"},
{type:"Newspaper", author: "Noke"}
]
Is still valid JSON (well actually keys need to be enclosed in " as well), so you can .push() into an array each time you create a JSON record.
var list = [];
// code doing other stuff
list.push({type:"book" , author: "Lian", Publisher: "ABC"});
// more code doing other stuff
list.push({type:"Newspaper", author: "Noke"})
Once your JSON list is constructed, you can send that list to the backend in one go.
You can also use the JavaScriptSerializer to deserialize your own custom type. Esentially you make a very simple type with all the properties of your json objects then call
JavaScriptSerializer serializer = new JavaScriptSerializer();
MyType result = serialzer.Deserialize<MyType>(JsonData);
You can also deserialize an array
MyType[] result = serialzer.Deserialize<MyType[]>(JsonData);

Categories

Resources