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

If you haven’t seen the part 1 of this, you can take a look over here, we learn alot of good things, check it out!

Today, we will learn to do more advanced things in JSON, are you ready?

Let’s back to basic!

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

Adding more properties

JSON is fantastic, absolutely, but in the beginning it’s strange to see if you never before develop an app using languages like Ruby.

Do you remember the last example we did it?

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

The last thing we learned was add arrays to JSON, but what about for example, imagine that you are developing an app that needs to know about the tastes of the people and a way to filter it?, well, with JSON it’s possible.

{
 "name":"Dark Mystical Cory",
 "age":29,
 "city":"México",
 "food": {
          "breakfast": ["Eggs and ham", "Hotcakes"],
          "lunch": ["Tacos", "Pizza"],
          "dinner": ["Salad", "Cereal"]
         },
 "colors": ["black", "blue", "yellow"]
}
"JSON Example with food categories"

You see what are we doing? Yeah, we add variables inside the food variable because we need it and it’s easy to read.

But we are not finished yet, because we also need to know the favorite/hate colors of people.

{
 "name":"Dark Mystical Cory",
 "age":29,
 "city":"México",
 "food": {
          "breakfast": ["Eggs and ham", "Hotcakes"],
          "lunch": ["Tacos", "Pizza"],
          "dinner": ["Salad", "Cereal"]
         },
 "colors": {
            "love": ["black", "yellow", "blue"],
            "hate": ["pink", "white", "red"]
           }
}
"JSON Example with food and colors categories"

In good words, when you see {} it’s because it’s an object, that is something to play with, and if you see [] it’s because it’s an array.

You got it, right? Before we continue, let’s code a little bit.

Facing JSON with categories

Like the last time, create a new console app in visual studio, and install the following package:

Install-Package Newtonsoft.Json

We are still using .NET Core because i like it, but if you want to, use .NET classic.

Imports System
Imports Newtonsoft.Json

Module Program
    Sub Main(args As String())
        Dim json = "{
    'name':'Dark Mystical Cory', 
    'age':29, 
    'city':'México',
    'food': {
                'breakfast': ['Eggs and ham', 'Hotcakes'],
                'lunch': ['Tacos', 'Pizza'],
                'dinner': ['Salad', 'Cereal']
            },
    'colors': {
        'love': ['black', 'yellow', 'blue'],
        'hate': ['pink', 'white', 'red']
    }
 }"
        Dim p = JsonConvert.DeserializeObject(Of Person)(json)
        Console.WriteLine($"Name: {p.name}")
        Console.WriteLine($"Age: {p.age}")
        Console.WriteLine($"City: {p.city}")
        Console.WriteLine("List of breakfast:")
        For Each food In p.food.breakfast
            Console.WriteLine(food)
        Next
        Console.WriteLine("List of lunch:")
        For Each food In p.food.lunch
            Console.WriteLine(food)
        Next
        Console.WriteLine("List of dinner:")
        For Each food In p.food.dinner
            Console.WriteLine(food)
        Next
        Console.WriteLine("List of favorite colors:")
        For Each color In p.colors.love
            Console.WriteLine(color)
        Next
        Console.WriteLine("List of colors that I don't like:")
        For Each color In p.colors.love
            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 food_categories
        Public Property colors As color_categories
    End Class

    Public Class food_categories
        Public Property breakfast As List(Of String)
        Public Property lunch As List(Of String)
        Public Property dinner As List(Of String)
    End Class

    Public Class color_categories
        Public Property love As List(Of String)
        Public Property hate As List(Of String)
    End Class
End Module

Wow, it’s quite of bigger this time, but don’t care about the size, like the last time, we need to focus just in this lines

Public Property food As food_categories
Public Property colors As color_categories

What are we doing? Well, we are creating a object that contains the lists of color and food categories. Yeah, its simple!

In the next post, we will teach you using a real world case on the web how to parse JSON.

Today we learned:

  • That i don’t like pink 😆 just kidding
  • Create object as values
  • How to add lists to variables
  • How to parse more sophisticated JSON

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…

1 year 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…

2 years 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

2 years 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…

2 years 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?

2 years ago

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

Looking my notes from the past, I saw that I always had problems with JSON, but first, what is JSON?…

2 years ago

This website uses cookies.