Categories: json net net core

How to: Parse JSON using .NET or .NET Core – Intro

Today, i was looking back in the past about a few problems that i had when i started working with web apps.

In fact, this was the first problem if i remember, it’s how to parse a json in .NET?

A few years ago, it was a really difficult problem, because of the documentation and stackoverflow has only information in other languages.

But in this age, it’s very simple, are you ready how to do it?

Let’s back to basic!

If you want to cheat and see the end, you can download the project from here

If you want to go directly to the solution: Click [here](Go-to-facing-json)

Prequisites

  • Visual Studio 2017, you can download the community edition here
  • Optional: If you want to use .NET Core, you need to download the installer here
  • And as always, a lot of desire to learn 🧙‍♂️

What is a JSON? How can i eat it? 🍕

Well the correct meaning is Javascript Object Notation, in a few words, is a syntax for storing (using no-sql dbs) and send/receive data.

Why is so popular? Because it’s very lightweight (comparing with XML for example)

But maybe it’s little confusing, so let’s start for the beginning.

{
 "name":"Dark Mystical Cory", 
 "age":29, 
 "city":"México"
}
"JSON Example"

The above, it’s an example of a basic JSON string, you can add whetever you want, like food, sports, everything. Let’s some add food.

{
 "name":"Dark Mystical Cory", 
 "age":29, 
 "city":"México",
 "food": ["Tacos", "Pizza"]
}
"JSON Example with Food"

Hold on, why do you add []?

Because with the brackets, you can assign an array to a variable in JSON, it’s a beautiful and easy way to add it. But i need to add my favorite colors.

{
 "name":"Dark Mystical Cory", 
 "age":29, 
 "city":"México",
 "food": ["Tacos", "Pizza"],
 "colors": ["black", "blue", "yellow"]
}
"JSON Example with Food and Colors"

You are already understanding it, right? Let’s code a little bit to understand even more.

Facing JSON ✨

Create a new console app in Visual Studio, and then, install the following package (don’t forget to save the project first):

Install-Package Newtonsoft.Json

I’m using .NET Core project, but it’s the same if you are using classic .NET.

Imports System
Imports Newtonsoft.Json

Module Program
Sub Main(args As String())
Dim json = "{'name':'Dark Mystical Cory', 'age':29, 'city':'México','food': ['Tacos', 'Pizza'],'colors': ['black', 'blue', 'yellow']}"
Dim p = JsonConvert.DeserializeObject(Of Person)(json)
Console.WriteLine($"Name: {p.name}")
Console.WriteLine($"Age: {p.age}")
Console.WriteLine($"City: {p.city}")
Console.WriteLine("My favorite food:")
For Each food In p.food
Console.WriteLine(food)
Next
Console.WriteLine("My favorite colors:")
For Each color In p.colors
Console.WriteLine(color)
Next
Console.ReadKey()
End Sub

Public Class Person
Public Property name As String
Public Property age As String
Public Property city As String
Public Property food As List(Of String)
Public Property colors As List(Of String)
End Class
End Module

Let’s check it out the most important part of the code.

Dim json = "{'name':'Dark Mystical Cory', 'age':29, 'city':'México','food': ['Tacos', 'Pizza'],'colors': ['black', 'blue', 'yellow']}"
Dim p = JsonConvert.DeserializeObject(Of Person)(json)

The first variable, it’s the same json string example we used before, but changing the double quotes to single quotes, because, we don’t want to get errors right? Nothing happens after we did this change.

With the second variable, we are deserializing the json string into a class Person to manipulate the information, easy right? That’s why we created the class Person below.

In other words, the “p” variable have now, all the information we assign before in the json string.

Today, we learn:

  • What is JSON
  • How-to add an array into a variable
  • How-to parse a json string

If you want to continue exploring this world and learn much more about JSON using .NET, click here

Are you in trouble? Have any questions? Contact me

dmcory @dmcory

I am a mexican Back-End Developer with 6 years of experience and 3 year of MSSQL Database Administrator. Experienced with all stages of the development cycle for web apps. Strong experience in project management and leadership.

Recent Posts

Fired IT guy deletes 23 AWS servers from his old company

A person from the systems area has been imprisoned after being fired for having bad performance, but how can he/she…

8 months ago

Thousands of Asus PCs infected with malware using their app for updates

The hackers sneaked in a back door using the Asus update software, targeting specific computers but affecting thousands of users…

8 months ago

Facebook stored millions of passwords in plaintext

Facebook confirmed thursday in they blog that they stored "hundreds of millions" password in plaintext FOR YEARS

8 months ago

Object-oriented programming: Intro

Today, we are facing what is the most important programming model and why is so popular, click and check it…

8 months ago

How to: Quickly get into Entity Framework

Let's talk a little bit about still using SqlCommand or migrate to Entity Framework, who will win?

8 months ago

How to: Parse JSON using .NET or .NET Core – Objects as values

It's time to another how-to series! This time we will learn about the object as values and how-to read it…

8 months ago

This website uses cookies.