【问题标题】:JsonSerializer.Deserialize exception: The JSON value could not be converted to System.StringJsonSerializer.Deserialize 异常:无法将 JSON 值转换为 System.String
【发布时间】:2022-01-01 16:49:15
【问题描述】:

我正在尝试读取这个 json 字符串 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}

这是 json 可视化工具的外观:

这是我正在使用的代码:

Metadata.cs(仅包括与错误相关的字段,因为其他字段正在工作)

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

错误消息: System.Text.Json.JsonException: '无法将 JSON 值转换为 System.String。路径:$.fitbit |行号:0 | BytePositionInLine:650。'

如何正确转换?

【问题讨论】:

标签: c# json


【解决方案1】:

您的 json 无效,其中一个属性 fitbit 具有字符串值,另一个显示为空数组。更改您的元数据类

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

或者修复你的 json

"fitbit" : "",

【讨论】:

  • 刚刚看到,当 json 字符串为空时,它以“[]”的形式出现,但当它有数据时,它不是数组。我将只设置一个 jsonstring.replace("[]", "\"\"");
  • @AdrianHernandoSolanas 请参阅我对您上一个问题的回答。这是相同的。不为空时是什么数据?
  • 用文本可视化器观看:"fitbit":{"food":30,"thirst":30}
  • @AdrianHernandoSolanas 总是一样吗?我的意思是当它不为空的时候?
  • 整数(食物,口渴)可以改变,但没有别的,架构总是相同的,但整数值可以不同。所以我可以得到 nill 或者我可以得到这 2 个值
【解决方案2】:

因为 fitbit 是一个空数组。它不是一个字符串。

【讨论】:

  • 承认@Serge 的答案排在您的后面,但它提供了一个很好的例子来说明如何回答这样的问题。您的答案是正确的,但 Serge 的答案通过添加额外的上下文和选项来解决问题更有用。
  • 谢谢,我会注意我的回答。
猜你喜欢
  • 2020-02-25
  • 2022-12-14
  • 2021-10-30
  • 2015-07-09
  • 1970-01-01
  • 1970-01-01
  • 2012-09-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多