-3

I have the following Json file:

{
    "@odata.context": "https://mmtruevalves.cc",
    "value": [
        {
             "Date": "2019-08-01T00:00:00-07:00",
             "TemperatureCelsius": 25,
             "Summary": "Hot",
             "Quantity":45.88

        }
    ]
}

And the following code:

 public class WeatherForecast
 {
     public DateTimeOffset Date { get; set; }
     public int TemperatureCelsius { get; set; }
     public string? Summary { get; set; }
     public decimal? Quantity { get; set; }
 }

    

 string jsonString = File.ReadAllText(fileName);
 WeatherForecast weatherForecast = 
 JsonSerializer.Deserialize<WeatherForecast(jsonString)!;

 
 Console.WriteLine($"Date: {weatherForecast.Date}");
 Console.WriteLine($"TemperatureCelsius: {weatherForecast.TemperatureCelsius}");
 Console.WriteLine($"Summary: {weatherForecast.Summary}");

I'm using the above code for class and processing but not getting desired results. I need proper class and processing so that I can get full results.

2
  • 1
    What is the desired result? Could you provide an example output of your desire and one output you currently get? from what i see you try to put the json into one object...which lacks an wrapper class since you use top-level object with an value array. have you already defined said wrapper class? if so can you provide it aswell?
    – LMA
    Commented 2 days ago
  • 5
    It is obvious, you should deserialize "value" part, not whole JSON string. Commented 2 days ago

1 Answer 1

1

jsonString is the outermost JSON object. This object contains two properties, @odata.context and value. The C# class you are mapping that object to, WeatherForecast, does not contain those properties.

You can make a type for the outermost class.

public class ODataResult<T>
{
    [JsonPropertyName("value")] public T[] Value { get; set; }
    [JsonPropertyName("@odata.context")] public string Context { get; set; }
}

Then deserialize the whole JSON in one go.

var result = JsonSerializer.Deserialize<ODataResult<WeatherForecast>>(jsonString);
        
Console.WriteLine(result.Value[0].Date);
Console.WriteLine(result.Value[0].TemperatureCelsius);
Console.WriteLine(result.Value[0].Summary);
Console.WriteLine(result.Value[0].Quantity);

Remember that the value of the value property in your JSON is an array of objects, not a single object.


The other method is to only deserialize just the value JSON property.

WeatherForecast[] forecasts = JsonNode.Parse(jsonString)
    .AsObject() // the outermost JSON is an object
    ["value"]   // get the "value" property from that object
    .Deserialize<WeatherForecast[]>(); // convert the array into C# objects.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.