Riccardo Pezzolati
Riccardo Pezzolati

Reputation: 359

JsonConvert deserialize only Class fields

This is json:

{
    "odata.metadata": ".....",
    "value": [
        {
            "AbsEntry": 10,
            "ItemNo": "....",
            "UoMEntry": -1,
            "Barcode": "2000000000022",
            "FreeText": "Ean13"
        }
    ]
}

This is class:

public class BarCode
{
     public int AbsEntry { get; set; }
     public string ItemNo { get; set; }
     public string Barcode { get; set; }
     public string FreeText { get; set; }
 }

This method return null:

BarCode barcode = JsonParser.DeserializeObjcet<BarCode>(json);

Are there any properties or other that can cause the call DeserializeObject to deserialize me only the fields of my classes (the names are exactly those of the Json)?

Upvotes: 2

Views: 1877

Answers (3)

xdtTransform
xdtTransform

Reputation: 2057

You are missing the root object :

public class RootObject
{
    public string __invalid_name__odata.metadata { get; set; }
    public List<BarCode> value { get; set; }
}

note that the invalid name oprperty can just be remove so it will be igrored!

Even if you want only the Value part you will have to deserialise from the root, then navigate to the child properties you need.

Upvotes: 3

CodeNotFound
CodeNotFound

Reputation: 23220

The structure of your class should match the structure of your JSON if you want the deserialization to succeed.

If you want a partial deserialization e.g. only deserializing the values property into your class you can use this code:

JObject jObject = JObject.Parse(json);
BarCode barcode = jObject["values"].Children().First().ToObject<BarCode>();

With this solution you don't need to refactor your class or adding a new one.

Upvotes: 3

Parth Akbari
Parth Akbari

Reputation: 651

You need to create class like below not BarCode

public class Value
{
 public int AbsEntry { get; set; }
 public string ItemNo { get; set; }
 public int UoMEntry { get; set; }
 public string Barcode { get; set; }
 public string FreeText { get; set; }
}

or you can change the JSON format

"BarCode": [
        {
            "AbsEntry": 10,
            "ItemNo": "....",
            "UoMEntry": -1,
            "Barcode": "2000000000022",
            "FreeText": "Ean13"
        }
    ]

Upvotes: 3

Related Questions