1

I'm trying to read this json string players.Metadata:

{"drunk":0,"isbleeding":false,"stress":5,"licences":{"drive_boat":false,"hunting":false,"business":false,"driver_bike":false,"dmv":true,"weapon":false,"drive_truck":false,"drive_fly":false,"driver":true},"tracker":false,"craftingrep":0,"commandbinds":[],"phonedata":{"SerialNumber":86505294,"InstalledApps":[]},"bloodtype":"B+","status":[],"walletid":"QB-40404499","poop":0,"isdead":false,"fingerprint":"NQ795L08aVN5152","jobrep":{"taxi":0,"trucker":0,"hotdog":0,"tow":0},"callsign":"NO CALLSIGN","armor":100,"hunger":83.19999999999709,"criminalrecord":{"hasRecord":false},"inside":{"apartment":[]},"inlaststand":false,"ishandcuffed":false,"fitbit":[],"attachmentcraftingrep":0,"inpdjail":0,"beard":0.0,"injail":0,"currentapartment":"apartment56922","jailitems":[],"phone":[],"clean":98.0,"dealerrep":0,"drug":0,"thirst":84.79999999999927}

This is how it looks with json visualizer:

enter image description here

This is the code I'm using:

Metadata.cs (only including field related to error as other fields are working)

public class Metadata
{
    /* All other fields are working or didn't step into them */
    public string fitbit { get; set; }        
}

Main.cs

Metadata metadata = new Metadata();
metadata = JsonSerializer.Deserialize<Metadata>(players.Metadata);

Error msg: System.Text.Json.JsonException: 'The JSON value could not be converted to System.String. Path: $.fitbit | LineNumber: 0 | BytePositionInLine: 650.'

How can I convert it correctly?

  • `[ ]` indicates that the data type is an array/list. Your `fitbit` property is declared as a `string`. Changing the data type to array should resolve the issue (as long as everything else is ok) – Anu6is Jan 01 '22 at 16:53
  • Please try changing the type from `string` to an array type, such as `object[]`. – Denis Akopyan Jan 01 '22 at 16:53
  • Does this answer your question? [How to handle both a single item and an array for the same property using JSON.net](https://stackoverflow.com/questions/18994685/how-to-handle-both-a-single-item-and-an-array-for-the-same-property-using-json-n) – Charlieface Jan 01 '22 at 18:40

2 Answers2

0

Because fitbit is an empty array. It is not a string.

Nihat Çelik
  • 29
  • 1
  • 4
  • 1
    Acknowledging that @Serge's answer came in after yours, it nevertheless provides a good example of how to answer questions like this. Your answer is correct, but Serge's answer is more useful by adding additional context and options for resolving the issue. – Jeremy Caney Jan 02 '22 at 00:14
  • 2
    Thank you, I will pay attention to my answers. – Nihat Çelik Jan 02 '22 at 03:44
0

Your json is invalid, one of the property fitbit has string value, another is shown as an empty array. Change your Metadata class

public class Metadata
{
   public object fitbit { get; set; }       
}

or fix your json

"fitbit" : "",
Serge
  • 40,935
  • 4
  • 18
  • 45