2

I'm tring to convert a string json to c# object,

I've already read several replies in here regarding to similar questions but none of the solutions worked.

This is the json obj

{
   "Customer": {
     "data_0": {
        "id": "273714",
        "FirstName": "Zuzana",
        "LastName": "Martinkova"
     },
     "data_1": {
        "id": "274581",
        "FirstName": "Ricardo",
        "LastName": "Lambrechts"
     },
     "data_2": {
        "id": "275190",
        "FirstName": "Daniel",
        "LastName": "Mojapelo"
     },
     "data_3": {
        "id": "278031",
        "FirstName": "Sulochana",
        "LastName": "Chandran"
      }
   }
}

I created the following objects according to the json obj

public class Customer
{
    public List<Data> Customers{ get; set; }
    public Customer()
    {
        Customers = new List<Data>();
    }
}
public class Data
{
    public string id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

As for my code I made a small console app example with all the solotions I found here

static void Main(string[] args)
{
    try
    {
        string jsonString = File.ReadAllText(ConfigurationSettings.AppSettings["filepath"].ToString());

        //solution 1
        JObject jsonone = JObject.Parse(jsonString);
        var collection_one = jsonone.ToObject<Customer>();

        //solution 2
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        var collection_two = serializer.Deserialize<Customer>(jsonString);

        //solution 2
        var collection_three = JsonConvert.DeserializeObject<Customer> (jsonString);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message); ;
    }

    Console.ReadKey();
}

Ths json string I get from a 3rd party webservice so just for the example I'm reading the json from a txt file,
the jsonString param value after reading is:

"{\"Customer\":{\"data_0\":{\"id\":\"273714\",\"FirstName\":\"Zuzana\",\"LastName\":\"Martinkova\"},\"data_1\":{\"id\":\"274581\",\"FirstName\":\"Ricardo\",\"LastName\":\"Lambrechts\"},\"data_2\":{\"id\":\"275190\",\"FirstName\":\"Daniel\",\"LastName\":\"Mojapelo\"},\"data_3\":{\"id\":\"278031\",\"FirstName\":\"Sulochana\",\"LastName\":\"Chandran\"}}}"

On every solution I make the collections count is 0, data objects are not including inside the list.

Can someone put some light on it and tell me what is wrong?
Thanks in advance

5
  • 1
    You need two classes, keep your Data class and you need another class that has a single Dictionary<string, Data> property called "Customer". If you want to have different C# property names then the JSON you need to use the JSON.NET [JsonProperty(name="")] attribute Commented Mar 26, 2018 at 19:10
  • @maccettura but I have 2 classes , 1 for the data and 2 has list<data> Commented Mar 26, 2018 at 19:12
  • Your JSON isnt a list though, its a dictionary. And your property is called "Customers" and your JSON is clearly labeled "Customer" Commented Mar 26, 2018 at 19:13
  • 1
    You don't have any object named Data, you have one data_01, and a data_02, etc, so, like @maccettura says, you do not have a list of Data, you have a Dictionary<string, Data>; Commented Mar 26, 2018 at 19:14
  • @maccettura Your solution solve it, I didn't realise a dictionary will act different. thanks Commented Mar 26, 2018 at 19:20

2 Answers 2

2

Your JSON is a Dictionary<string, Data>, not a List<Data>. In addition to that your property is called "Customer", not "Customers". To solve this you need to change a couple things:

public class Customer
{
    //JsonProperty is Used to serialize as a different property then your property name
    [JsonProperty(PropertyName = "Customer")] 
    public Dictionary<string, Data> CustomerDictionary { get; set; }
}
public class Data
{
    public string Id { get; set; } //You should make this "Id" not "id"
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

With these class definitions you can easily use the JsonConvert.DeserializeObject() and JsonConvert.SerializeObject() methods:

Customer customer = JsonConvert.DeserializeObject<Customer>(json);
string newJson = JsonConvert.SerializeObject(customer);

I made a fiddle here to demonstrate.

Sign up to request clarification or add additional context in comments.

Comments

0

You can try this one.

Add empty class public class Customer : Dictionary<string, Data>{} //empty class

And the update your existing code

//solution 1    
JObject jsonone = JObject.Parse(jsonString);

//Add this line
var token = jsonone.SelectToken("Customer").ToString();

//solution 2 - update jsonString to token variable created above.
var collection_three = JsonConvert.DeserializeObject<Customer>(token);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.