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.
Related
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)
I can't seem to wrap my head around JSON in C#. I use JSON.NET and usually I can figure out the class needed to convert. However in this case it's challenging: there is no name for the individual list items.
{"error":[], "result":{"currency":[[2.0, 3.0, 4.0, 5.0], [6.0, 7.0, 8.0, 9.0], ... ]}}
This is an example from memory, I hope the syntax is right.
So, when I attempt to create the classes, I don't know where to start. Say, I am interested in the result pair. Is "currency" a list of lists? How would I map the value for the list (2.0, 3.0, 4.0, 5.0) and its enclosing result?
Not sure at all...
Currency is a list of lists of double. Your Result object should look something like:
public class Result {
List<List<double>> Currency {get;set;}
}
Additionally, Visual Studio has a 'Paste Special' option under the Edit Menu that can be used to turn an XML or JSON string from the clipboard into C# classes that conform to the structure.
To avoid any probability of errors, you can do like this: copy your JSON file, go to Visual Studio=>Edit=>Paste Special=>Paste JSON as class. This will generate the classes for you.
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 Foursquare app for Windows Phone 7. It's working nicely with HttpWebRequests and I'm receiving JSON objects perfectly. I'm using the DataContractJsonSerializer(type) method. But when deserializing this JSON to the object I want, It all goes well until I there's and array of objects, where I don't know which object-type to expect (also don't know the amount & order of objects). But I do need to define this type when deserializing in the method DataContractJsonSerializer(type).
Let me show you a snapshot of JSON which causes the trouble:
notifications":
[{
"type":"notificationTray",
"item":{
"unreadCount":0
}
},{
"type":"message",
"item":{
"message":"OK! We've got you # Strandslag 4. You've been here 2 times."
}
}]
So I'm deserializing this to an array of Notification objects, with two memers: "public String type" and an "public Object item". I can't know which, and how many, Notification's there will be in the array (and thus of what type the 'item' member must be). As you can see in the JSON, the first notification has an item of type int, but the second notification's item is of type string. But I need to know that for the deserialization... Or else it just stays null.. So I cant cast it to the correct type..
Does anyone knows how to solve this nicely?
Hmmm not 100% sure this will answer your question but can you not use javascript to convert whatever the object is into a string and then manipulate it that way?
Something like:
var value = whatever[number].toString;
This would give you a string you can work with. You could then try to parse it back to an int.
var valueInt = parseInt(value);
Then use an IF statement to see if the valueInt exists or not to determine what kind of value the first object has.
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);