Click here to Skip to main content
15,883,767 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
If my string(json) contain only following part, I am able to deserialize it with the help of newtonsoft's library.

{"Code": "MXXXXX", "Status": "failed"}

Code to deserialize:

public class Account
{
public string Code{ get; set; }
public string Status{ get; set; }
}
Account account = JsonConvert.DeserializeObject(json);

Console.WriteLine(account.Code);

But if my string is like this:

{'data': ' {"Code": "MXXXXX", "Status": "failed"}'}

I am unable to deserialize. Here the class has only one property which is data... how can I do that?

What I have tried:

Code to deserialize:

public class Account
{
    public string Code{ get; set; }
    public string Status{ get; set; }
}
Account account = JsonConvert.DeserializeObject(json);

Console.WriteLine(account.Code);
Posted
Updated 8-Feb-17 1:17am
Comments
dan!sh 8-Feb-17 6:25am    
This does not look correct JSON (not syntactically). 'data' in your JSON will be deserialized as string due to additional quotes around the desired data.
F-ES Sitecore 8-Feb-17 6:27am    
You need a class with a property called "data" that is of type "Account" and you deserialise to that class. You might also need to update your source string to

{'data': {"Code": "MXXXXX", "Status": "failed"}}

Note I removed some apostrophes

try this

static void Main(string[] args)
       {
           string json = "{'data':  {\"Code\": \"MXXXXX\", \"Status\": \"failed\"}}"; // take care of the json, it should be a valid json format
           MyAccount account = JsonConvert.DeserializeObject<MyAccount>(json);
           Console.WriteLine(account.data.Code);

       }


public class MyAccount
   {
       public Account data { get; set; }
   }
   public class Account
   {
       public string Code { get; set; }
       public string Status { get; set; }
   }
 
Share this answer
 
v2
Check this out: Deserialize JSON to class in C#[^]
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            string json = "{\"data\":{\"Code\": \"MXXXXX\", \"Status\": \"failed\"}}";

            var jsonObj = JsonConvert.DeserializeObject<JObject>(json).First.First;
		
            Console.WriteLine(jsonObj["Code"]);
        }

        public class Account
        {
            public string Code
            {
                get;
                set;
            }

            public string Status
            {
                get;
                set;
            }
        }
    }
}
Reference: JObject Class[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900