Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Create a .NET object for JSON serialization and deserialization [duplicate]

Tags:

json

c#

I'm working on a point system for my twitch chat bot in C#. I need to save a list of users with their amount of points and hours to a local .txt file like this:

  • users : ???
    • username : ???
      • nick : string
      • points : int
      • hours : int
    • username : ???
      • nick : string
      • points : int
      • hours : int
    • username : ???
      • nick : string
      • points : int
      • hours : int

I'm trying to create a .NET Object to serialize to a JSON string and write this to my .txt file but I'm stuck here.

I figure users needs to be an Array of some sort but what do I do with username? I don't think JSON supports custom types?

Thanks for your time, X3ntr

like image 874
X3ntr Avatar asked May 13 '16 17:05

X3ntr


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr. Stroustroupe.

Is C programming hard?

C is more difficult to learn than JavaScript, but it's a valuable skill to have because most programming languages are actually implemented in C. This is because C is a “machine-level” language. So learning it will teach you how a computer works and will actually make learning new languages in the future easier.


2 Answers

First we need to create a model. This model needs to match the structure of the JSON. There are a couple of ways to create this model.

Probably the best and safest way is to write it manualy. If you are using vs2015 you can also copy the json and paste it as class.

You can find this option here: enter image description here

Another option is to use a website like http://json2csharp.com/ here you can paste the JSON and this will also generate classes for your JSON. Keep in mind that these generator are not 100% accurate so you might have to change some properties your self.

Ones we got the model we can use a lib like JSON.net to Deserialize our JSON. On the website is also some extra documentation on how to use JSON.net

var userList = JsonConvert.DeserializeObject<List<UserModel>>(users); //Users being the json as text.

Remember that if you miss a property in you model this will not always throw an error. So make sure that all properties got serialize correctly.

Serializing is as simple as Deserializing.

string json = JsonConvert.SerializeObject(model);
File.WriteAllText("C:\json.txt",json); 

Optional is adding an encoding when writing the json.

File.WriteAllText("C:\json.txt",json,Encoding.UTF8);
like image 163
Florian Schaal Avatar answered Oct 19 '22 17:10

Florian Schaal


I'll take a shot at it.

First up we'll need a model for our user:

public class User
{
    public Guid Id { get; set; }
    public string Username { get; set; }
    public string NickName { get; set; }
    public int Points { get ;set; }
    public int Hours { get; set; }
}

Then in your main method, or wherever you deal with your users:

List<User> users = new List<User>();

Notice that I've added an Id property. Even though your usernames might very well be unique, it's always good practice to have some sort of property whose entire job is to just be the Id. This property should never change throughout the lifetime of the user. Where username might change one day, the Id will always stay the same.

Anyways, now to turn your list into Json:

string myJsonString = JsonConvert.SerializeObject(users, Formatting.Indented);

Et voila! Your list of users is now in a tidy Json string. The above line of code is from JSON.NET, you can get it as a Nuget package. The full qualification is Newtonsoft.Json.JsonConvert. You can pretty much trust JSON.NET to handle almost anything you throw at it, especially for a simple User class like you're going to be throwing at it.

Hope this helps get you started.

like image 7
Grace Atwood Avatar answered Oct 19 '22 18:10

Grace Atwood