What's causing JsonException: The JSON value could not be converted?
Asked Answered
F

3

15

C# 10 / .NET 6 / System.Text.Json

I'm working with an API that returns as JSON response. I'm trying to use System.Text.Json to deserialize the JSON response into a class. I'm receiving a JsonException and could use help understanding what I'm doing wrong.

I call the API and store the JSON response: string json = await Retreive.Fetch(target);

Here's the output of Console.WriteLine(json):

[{"id": 1148082,"name": "TestGroup","group_type":"console_group","provisioning_guid": null,"member_count": 1,"current_risk_score": 36.3,"status": "active"},{"id": 1148788,"name": "Group2","group_type": "smart_group","provisioning_guid": null,"member_count": 9,"current_risk_score": 39.7,"status": "active"},{"id": 1148792,"name": "Group3","group_type": "smart_group","provisioning_guid": null,"member_count": 9,"current_risk_score": 39.7,"status": "active"}]

Here's a pretty-printed version if it helps:

[
  {
    "id": 1148082,
    "name": "TestGroup",
    "group_type": "console_group",
    "provisioning_guid": null,
    "member_count": 1,
    "current_risk_score": 36.3,
    "status": "active"
  },
  {
    "id": 1148788,
    "name": "Group2",
    "group_type": "smart_group",
    "provisioning_guid": null,
    "member_count": 9,
    "current_risk_score": 39.7,
    "status": "active"
  },
  {
    "id": 1148792,
    "name": "Group3",
    "group_type": "smart_group",
    "provisioning_guid": null,
    "member_count": 9,
    "current_risk_score": 39.7,
    "status": "active"
  }
]

Using Visual Studio 2022's Paste JSON As Classes function, I get the following class structure:

public class Rootobject
{
    public Class1[] Property1 { get; set; }
}

public class Class1
{
    public int id { get; set; }
    public string name { get; set; }
    public string group_type { get; set; }
    public object provisioning_guid { get; set; }
    public int member_count { get; set; }
    public float current_risk_score { get; set; }
    public string status { get; set; }
}

I'm trying: Rootobject? gag = JsonSerializer.Deserialize<Rootobject>(json);

A JsonException is thrown:

Unhandled exception. System.Text.Json.JsonException: The JSON value could not be converted to KB4.Rootobject. Path: $ | LineNumber: 0 | BytePositionInLine: 1. at System.Text.Json.ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(Type propertyType) at System.Text.Json.Serialization.Converters.ObjectDefaultConverter1.OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value) at System.Text.Json.Serialization.JsonConverter1.TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value) at System.Text.Json.Serialization.JsonConverter1.ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state) at System.Text.Json.JsonSerializer.ReadFromSpan[TValue](ReadOnlySpan1 utf8Json, JsonTypeInfo jsonTypeInfo, Nullable1 actualByteCount) at System.Text.Json.JsonSerializer.ReadFromSpan[TValue](ReadOnlySpan1 json, JsonTypeInfo jsonTypeInfo) at System.Text.Json.JsonSerializer.Deserialize[TValue](String json, JsonSerializerOptions options) at KB4.Kb4.Main() in C:<REDACTED>\Program.cs:line 188 at KB4.Kb4.()

Some things I have tried:

  • Changing the name of the Rootobject class to GetAllGroups
  • Thinking the JSON may be somehow malformed in the response, I pasted it into a text file and load the JSON from there and then attempt deserialization again.
  • Reviewed Deserialize a JSON array in C# but that's using JavaScriptSerializer.

Neither of the above produces a different result.

What am I doing wrong?

Flip answered 8/2, 2022 at 18:21 Comment(2)
Try this - var gag = System.Text.Json.JsonSerializer.Deserialize<List<Class1>>(json);Trochal
That works! Thank you @Serge! Can you help me understand why my original method did not work?Flip
T
14

your Rootobject class would be working if your json starts with this

{ "property1": [{"id": 1148082,"name": .....] }

and the array had a property name. but your json don't have property1, so you should start to deserialize json array directly

Class1[] result = System.Text.Json.JsonSerializer.Deserialize<Class1[]>(json); 
Trochal answered 8/2, 2022 at 19:2 Comment(0)
D
-1

would it have been easier and a lil bit more straight forward to just fix the json and add your class's property1

tmp = Regex.Replace(Result, @"^\{(.*)", "{\"property1\":{$1");
Result = tmp;
tmp= result+"}";
result=tmp;

...and do the decode voodoo...

Door answered 26/1 at 3:7 Comment(0)
P
-2

However, as @serge pointed out, your deserialize with Rootobject would work if the response was with a property1. However, adding to what @serge mentioned, the following should also work; given that @serged used an array but I used a List<T>:

var response = JsonSerializer.Deserialize<List<Class1>>(json);
Placidia answered 9/1 at 8:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.