Trying to deserialize the following json string:
string json = "{"d":{"__metadata":{"id":"http://my.dev.int:8000/sap/opu/odata/sap/ZFIORI_SERIAL_NUMBERS_SRV/MATERIALSet('250')","uri":"http://my.dev.int:8000/sap/opu/odata/sap/ZFIORI_SERIAL_NUMBERS_SRV/MATERIALSet('250')","type":"ZFIORI_SERIAL_NUMBERS_SRV.MATERIAL"},"MATNR":"250","MAKTX":"X:K10/MF250"}}";
into Class Object
namespace Scanner.Model
{
public class Material
{
public string MATNR { get; set; }
public string MAKTX { get; set; }
}
}
I have tried using many ways including :
Material material = JsonSerializer.Deserialize<Material>(json, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
IgnoreNullValues = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
});
Console.WriteLine(material.MATNR); //expected output: 250
Console.WriteLine(material.MAKTX); //expected output: X:K10/MF250
But material.MATNR and material.MAKTX are always null .
2
Answers
I think you need to familiarize yourself more with the Json structure,
Material
is not the type of object being returned in your Json string, it is a nested class of the main object, I have put together a dot net fiddle and tested that this will work for you, as you can see, the main object is what I calledMyJson
which holds one property of class typeMetaData
and a property name ofd
, this class then contains 3 properties: of typeMetaBase
which contains 3 properties ofstring
types and 2 otherstring
properties, I then deserialize the json string to the main object type ofMyJson
and then write the nested propertyMATNR
to the console window, this prints 250, I’m also using,JsonPropertyNameAttribute
to set certain class properties to the matching values in the json string, you can read more about that here:system.text.json.serialization.jsonpropertynameattributefiddle here: dotnet-fiddle:
Since you need only Material