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)
Related
Suppose I have a JSON request body req1, and it resulted in a JSON response resp1, some of whose key-values are identical to those in req1. Now suppose I have another JSON request req2, and I want to construct a JSON response resp2 which is a duplicate of resp1, but in which the common keys have their values replaced by the values from req2.
What strategy might be used to tackle this?
As a concrete example, suppose req1 is this:
{"Name":"Alan"}
And suppose this is resp1:
{"output":{"Name":"Alan", "Cat": "12"}}
Note that "Name":"Alan" appears in both.
If req2 is this:
{"Name":"Bancorp"}
Then I'd like to create resp2 from resp1 like this:
{"output":{"Name":"Bancorp", "Cat": "12"}}
Crucially, the document structure of req* and resp* are not known in advance, and the only knowledge is that the structure of req1 and req2 are similar, and likewise for resp1 and resp2.
In other words, I'm looking for a flexible pattern-recognition that will "learn" from an initial req1/resp1 pair by identifying fields that occurred in both, and then be able to respond to future req* inputs by making the proper substitutions to a copy of resp1.
Is this something which already exists? If not, how might it be implemented in JSON.Net?
I would deserialize your requests into separate objects first. You could then use reflection to get a list of all the properties of each object and filter the results to only show the common properties.
obj.GetType().GetProperties();
Once you have your list of properties that you need in the response object, you can create a new ExpandoObject and dynamically add the properties and corresponding values that you need.
dynamic x = new ExpandoObject();
x.NewProp = string.Empty;
Once you're done, you can serialize this response object back to JSON.
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.
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
});
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.
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);