RAMAN BHATIA
RAMAN BHATIA

Reputation: 427

How to deserialize Json to an object?

I want to convert json to a specific object.

String : "{\r\n \"Status\": \"PLANNED\"\r\n}"

I tried Newtonsoft Json namespace but it is returning a null value.

var Json= Newtonsoft.Json.JsonConvert.DeserializeObject<Model Class>(String )

I want the result in Json format so that I can extract the value from Json as "PLANNED" but I am getting a null.

PS :The model class contains two properties , Name (type of string), Value(type of Object)

Upvotes: 2

Views: 6009

Answers (3)

0x53olution
0x53olution

Reputation: 389

You can do it like this (using Newtonsoft Framework)

using System;
using Newtonsoft.Json;
{
    public class JsonHandler : IJsonHandler
    {
        public IJsonModel ReadJson(IJsonModel model, StreamReader reader)
        {
            try
            {
                string jsonFromFile;
                using (reader))
                {
                    jsonFromFile = reader.ReadToEnd();
                }

                status = JsonConvert.DeserializeObject<model>(jsonFromFile);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            return status;
        }
    }
}

Upvotes: 0

sayah imad
sayah imad

Reputation: 1553

JSON Definition

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language.

[Source] https://www.json.org/

JSON Newtonsoft

Json.NET is a popular high-performance JSON framework for .NET .

[Source] https://www.newtonsoft.com/json

Problem :

Your are trying to deserialize a json to an object and it's returning a null. In our context a Deserialization is process which transform a json to an object .

var Result= Newtonsoft.Json.JsonConvert.DeserializeObject<Model Class>(String);

The reason why you have a Null as result is beacause you are deserializing a json to Model, knowing that you Json does not correspond to the Model , this is why the Json need to correspond to the Model so that it can store the information of the Json.

Your Model :

The model may contain some property that are not in the json and vice versa

public class StatusModel
{
   public string Status { get; set; }
}

Best Regards .

Upvotes: 0

OhmnioX
OhmnioX

Reputation: 483

var s = "{\r\n  \"Status\": \"PLANNED\"\r\n}";
var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<StatusModel>(s);

The model you have defined is incorrect. Your model should be like this:

public class StatusModel
{
    public string Status { get; set; }
}

Now value will be extracted to this model and you can access the value like:

var value = obj.Status; //"PLANNED"

Upvotes: 5

Related Questions