In a world full of C# we go Back to Basic!

READ MORE
jsonnetnet core

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

.

March 5, 2019 by

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
Written by

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.

TOP
Copied!