This is the best json library I've found for C#: http://www.newtonsoft.com/json
Read through it, it's actually super simple to use but also offers a ton of power if you need it. And it can also be installed from nuget so you don't need to download and reference it manually.
-1. To get the data you can just use the "WebClient" class and its "DownloadString" method (details here
-2. Use NewtonSoft Json for parsing JSON to Objects (here
-3. You can for example add "ListView" to your view and then set it's source to the list of objects you created in step 2
-5. (before I get back to 4).
You can create a data template. Something like this:
<ListBox Width="400" Margin="10" x:Name="List"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock Text="{Binding Path=ArticleTitle}" /> <Image Height="40" Width="40" Source="{Binding Path=SourceOfYourIMage}"/> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox>
-4. Add a click event to the Stackpanel and then handle it in code behind. You can also create custom commands using MVVM which I would recommend (MVVM light might be good. Check out this)
I would really recommend you to get familiar with the MVVM pattern since this will make your code a lot easier.
Happy coding and Merry Christmas :)
You can use Newtonsoft.JSON. It's a free NuGet library that deserializes JSON into a C# object, called JSON.NET that you can then work with and manipulate in your code. Here's a link to their site: (http://www.newtonsoft.com/json). Also, here's some sample code that may assist you in understanding and learning how it all works: http://www.newtonsoft.com/json/help/html/Samples.htm. Hope that helps!
...but that's totally wrong.
Serialization is is the process of transforming a structured state - typically an object - into "something else." This "something else" can be anything, depending on what you want to do with the serialized data, but typically it's for making it possible to transfer it somewhere so that it can be...
...deserialized, which is the exact same thing, only the other way around: you take a serialized "something" and convert it to a structured state - again, typically an object - within your application.
Typically (these days), (de)serialization is necessary when you want to transfer complex structured states across the network; you usually serialize a structured state into JSON (or similar), transfer it as plain text over the network, as strings are easy for any network protocol to deal with, and then reconstruct/deserialize the data into a structured state on the other end.
It has nothing to with loading, destroying, saving and what not per se. That's something that must be handled outside of the (de)serialization process itself. Same goes with the (de)serialization processes(es) themselves; Unity's built-in stuff is mostly useless, so you might find yourself cornered one day having to deal with stuff otherwise.
My suggestion is to use Json.NET for this kind of jobs until you are familiar with more complex (de)serialization techniques in case you need more efficient solutions.
We've only ever needed a true deep clone once, and we cheated by serializing/deserializing it using <strong>json.net</strong>. Wish I had thought of the approach laid out by /u/Panaetius. That is more efficient than our way for sure.
You can use Newtonsoft.Json
to validate your JSON; just import the dll with Add-Type -Path ${path_to_newtonsoft.json.dll}
and have a look at this
In JSON.NET you can configure it to add a $type
information to allow serialization and deserialization of arbitrary types, often used for serializing polymorphic data structures. This is a potential security issue when deserializing, because users can send a completely unrelated $type
from the .NET framework and JSON.NET will happily deserialize to it.
If you use any other value than TypeNameHandling.None
(the default) you're potentially at risk: http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_TypeNameHandling.htm
Consider using Serialization.
There are tons of libraries for .NET to (de)serialize objects. I recommend Newtonsoft's JSON.NET for it's simplicity. Create a class that will be your Business Object which has all properties you need (Window Size, Window Position, and others) and the serialize it in e.g. a .Save() method with JsonConvert.SerializeObject(...);. I'm sure you will be able to figure this out on your own.
Edit: Should've read the whole code - you're already using XML serialization..
It's a good idea to have a class/struct that holds properties (e.g. "Preferences"), and a PreferencesManager that will have the Preferences Load()
and void Save(Preferences prefs)
(static) functions. This way you can easily add new properties only by adding them in the Preferences class/struct.
If you really wanted to save "a form" then override the form's properties you want to use, and mark them as Serializable. Then you can just serialize the form object (.NET's default XML serialization will only serialize properties with the [Serializable]
Attribute). (I wouldn't recommend you doing this though)
> THREAD name : Need help figuring out how to parse JSON data
Use Newtonsoft for this http://www.newtonsoft.com/json/help/html/DeserializeObject.htm
You can also autogenetate classes with this website http://json2csharp.com/
About why it doesnt post, its best you see if there is an exception and what it says.
> using (WebClient client = new WebClient())
Is useless since you dont use client
If the data you're getting back fromthe API call is in JSON format, you can use a deserializer to deserialize it into an object and translate the object to put it inot SQL (using EF or SQL Insert statements). Please check below for sample deserialization in C#: http://www.newtonsoft.com/json/help/html/DeserializeObject.htm
This is JSON.NET which has become the standard library for working with JSON. Even microsoft uses it for their frameworks.
There is a built in json serializer but it doesn't perform well and in JSON.NET just works better.
For 3 and 4 I sadly can't help you, I haven't checked out twitchs API but what you wrote about 3 sounds right in general.
can't you just use json.net and not write a parser? i.e.
http://www.newtonsoft.com/json
string json = @"{ 'Name': 'Bad Boys', 'ReleaseDate': '1995-4-7T00:00:00', 'Genres': [ 'Action', 'Comedy' ] }";
Movie m = JsonConvert.DeserializeObject<Movie>(json);
string name = m.Name; // Bad Boys
///////////////////////////
public class Wrapper{ public List<Zone> zone_list {get;set;} }
public class Zone{ public int int_1 {get;set;} // etc }
http://www.newtonsoft.com/json/help/html/DatesInJSON.htm
Also remember that this actually produces milliseconds past epoch. If you're looking for unix time, that's actually <em>seconds</em> past epoch.
Hm. Ok, this surprises me... Maybe this is a restriction peculiar to Unity? But, I mean... Serializing dictionaries is pretty mundane for the rest of us.
http://www.newtonsoft.com/json/help/html/SerializeDictionary.htm
Worst case, a dictionary is just a set of objects, each associated with a given key. You can absolutely just spit out the key followed by the serialized data of the object associated with it, and then you can read that back in the way you wrote it. No big deal.
Go with the custom converter, but the better option is to refactor the API. If you cannot change the API data contract then the custom converter works since you can use the JSONReader to determine if the token is a boolean or something else. http://www.newtonsoft.com/json/help/html/CustomJsonConverter.htm
This is what I mentioned before, but now I see the inconsistent return types: Use the JsonProperty attribute: http://www.newtonsoft.com/jsonschema/help/html/GenerateWithJsonNetAttributes.htm
Or if you have the time write a custom converter for better speed. If serialization / serialization isn't your bottleneck, then you can go with the attribute.
Just to add this to mix: I have been using JSON for storing data in my latest work and I really like it. I don't have to write any complicated parsing logic and just use JSON.NET which automatically hydrates objects. The older versions work fine with Unity / Mono, it's really light weight, JSON is very readable (unlike XML), tolerant to missing data (i.e. you can set defaults), etc, etc.
It's probably not ideal for a huge datasets though.
I think your best bet is to go with http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Converters_CustomCreationConverter_1.htm
Inherit it as class MemberCollectionCreationConverter : CustomCreationConverter<MemberCollection>
and override correct function where you can intercept the actual json data coming in and use jsonconverter on that, then determine if the root element is array and continue with deserializing into real Member objects int "MemberCollection" (which could even be List<Member> as base).
I think you'll need to override Create()
to create the MemberCollection and probably ReadJson
.
Here is how you'd then use the converter: http://www.newtonsoft.com/json/help/html/DeserializeCustomCreationConverter.htm
FWIW, whoever did that switcheroo is a retarded fuck.
I would suggest you check out the JSON.NET library (http://www.newtonsoft.com/json). This makes it simple to serialize various .Net types to JSON, including string arrays.
They have a bunch of code samples, here : http://www.newtonsoft.com/json/help/html/Samples.htm
Hope that helps. Enjoy!
Since you are learning new thigs, it might be good to try out Json.net for storing state in json files:
http://www.newtonsoft.com/json/help/html/SerializeWithJsonSerializerToFile.htm
http://www.newtonsoft.com/json/help/html/DeserializeWithJsonSerializerFromFile.htm
heh. I've heard/read the word but never need to look into it. I did however and it is pretty freaking awesome. Ended up going with Json.Net http://www.newtonsoft.com/json
Super ridiculously simple.
I did what you advised and everything seems to work great. Just using a List for my collection of objects and the Linq queries are fast and everything is good.
I appreciate your help. I'm glad I needed to look up JSON holy hell have i been doing it wrong for a while.
C# doesn't have dictionary literals, and C# objects are not just dictionaries anyway. You can deserialize JSON into C# objects if that's what you're looking for- there's a couple different deserializers built-in but the general consensus is to use the 3rd party JSON.NET.
Alternatively, you could do this part in F# which does have object literals. See here. You'd have to define this in a separate DLL because I don't think .NET supports compiling multiple languages into a single file yet, but it will show up in C# as a normal class.
Think I would prefer a custom serializer/deserializer (doc ).
You should be able to make it work with attributes as others have stated but I'm not a fan of decorating base models like that (really is up to the implementation in my mind to dictate that info). What happens if you implement another service call that fills the same model but returns the data in a slightly different structure?
To be fair, I'm a little biased towards hating serialization decorators from xml serialization days. Would end up with classes where 75% of the lines were serialization attributes or instructions....just seemed dirty and wrong.
http://www.newtonsoft.com/json
Deserializing a Jason string into an object is as simple as:
Movie m = JsonConvert.DeserializeObject<Movie>(json);
No try's, just a straightforward function call which will let you know if there are any problems. You can optionally add decorators to the class properties specifying the json key that should be used to populate it, but it's pretty good at figuring out the correct keys on its own.
Use JSON.NET You can add it as a Nuget package (it's free) then just deserialize the json into a collection like so http://www.newtonsoft.com/json/help/html/deserializeobject.htm
Just a word of warning, this repository contains compiled code in the form of DLL's. One seems to be to be a JSON parser, while the other seems to be a wrapper for the Reddit API. They are very probably fine, but seeing as they are compiled, there is no way to easily verify that they are.
If you want to be absolutely sure that there is nothing wrong in these DLL's, get them from the source, here and here. You will have to compile the Reddit API wrapper yourself, which is the same process as you'll need to do for the rest of this project. You'll have to open the project file (.sln) in Visual Studio and compile it. The output will be somewhere in a debug, release or bin folder.
Great write up! I'm really happy that you decided to separate the concept into what works best for each type of situation.
I'll add that if you're looking for a reusable-in-any-software format, JSON is a pretty great choice.
Some ideas:
With http://www.newtonsoft.com/json
dynamic dynamicJson = JsonConvert.DeserializeObject(json)
With your dynamic object you can iterate it for the field name you want
Anyway, you're making it quite hard for yourself. It would be much easier if you could tell the JSON parser where to look for your value.
http://stackoverflow.com/questions/21678126/parse-json-string-to-find-and-element-key-value
Could you build a JSON object out of the reader and then use JSON.Net to deserialize it? Sure, that uses reflection internally, but sometimes dumb requirements require dumb workarounds. It also has benchmarks.
> http://www.newtonsoft.com/json/help/html/Samples.htm
So is Serialising what I am looking to do in terms of the sample on the second pages? Thats more than enough to get me on the right track. Thank you !
I would just use Json.NET.
To serialise, you just use File.WriteAllText("C:\Path\To\Settings\File", JsonConvert.SerializeObject(options))
.
To deserialise, you just use JsonConvert.DeserializeObject<Dictionary<string,string>>(File.ReadAllText("C:\Path\To\Settings\File");
I have ported Json.Net to work under Unity.
You can get the code here: https://github.com/codecapers/Unity.Newtonsoft.Json
You can also install a pre-built dll via Nuget: https://www.nuget.org/packages/Unity.Newtonsoft.Json/
To use this you need to go into Player Settings and change 'Api Compatibility Level' from '.NET 2.0 Subset' to '.NET 2.0'.
If you want to use it and have problems getting it working please log an issue on github and I'll help you out.
Json.net: http://www.newtonsoft.com/json
I'm not quite sure if this is what you're asking, but if you're concerned about memory usage while parsing large JSON structures, you can use Json.NET's JsonTextReader to read JSON token by token without constructing the entire object graph.
If you can't change the JSON, and you need to deserialize the More object to a string; you must use a custom converter. They're easy to implement.
http://www.newtonsoft.com/json/help/html/CustomJsonConverter.htm
It's not supported by default as there are a lot of possible interpretations for the behavior of a generic. You want to create your own converter and use the JsonConverterAttribute to mark your classes. Since you inherit JsonConverter when you make your implementation you get all the Json serialized in a token object and you only need to handle processing of the special steps you want for generics. After that you can let the framework do it's thing.
Or you can centralize your access and use the converter directly though IMO that tends to make your integration code more complex.
My preferred method is to make a class to store all of that state, then use json.net to dump it to a file. Read the file in when they click the load button and call Deserialize on it and you have your state object back.
I dropped your code into my unity project (I use newtonsoft), and it works fine... Have you tried running it in an empty unity project, with your newtonsoft reference? I'm not sure what's at play but it doesn't appear specific to this code.
It's a shot in the dark, but if your problem is specific to arrays there are some collection attributes like JsonArrayAttribute that can affect how the array is serialized.
For interacting with APIs you're shooting yourself in the foot using standard C# classes like webclient
With webclient you can do some more shady stuff but that is beyond the scope of your article
Use restsharp instead http://restsharp.org/
Why do you use json2sharp by the way? With json.net you can deserialize from dynamic http://www.newtonsoft.com/json
Use it like this
string json = @"{'employees':[ {'firstName':'John', 'lastName':'Doe'}, {'firstName':'Anna', 'lastName':'Smith'}, {'firstName':'Peter', 'lastName':'Jones'} ]}";
dynamic dynamicJson = JsonConvert.DeserializeObject(json);
dynamic employees = dynamicJson.employees; /*
{[ { "firstName": "John", "lastName": "Doe" }, { "firstName": "Anna", "lastName": "Smith" }, { "firstName": "Peter", "lastName": "Jones" } ]}
*/
dynamic firstEmployee = dynamicJson.employees[0]; /*
{ "firstName": "John", "lastName": "Doe" }
*/
dynamic firstEmployeeFirstName = dynamicJson.employees[0].firstName; // {John}