Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JsonConvert deserialize only Class fields

Tags:

c#

json.net

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)?

like image 565
Riccardo Pezzolati Avatar asked Apr 25 '26 03:04

Riccardo Pezzolati


2 Answers

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"
        }
    ]
like image 172
Parth Akbari Avatar answered Apr 27 '26 17:04

Parth Akbari


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.

like image 35
CodeNotFound Avatar answered Apr 27 '26 15:04

CodeNotFound



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!