JSON with 'c#的子字段

本文关键字:字段 with JSON | 更新日期: 2023-09-27 17:51:19

我试图使用JSON反序列化以下JSON(我不控制源)。NET转换为一个或多个c#类失败。我如何处理"错误"字段。它似乎由一个整数和一个字符串组成,但这些子字段没有命名。

{
  "status": "error",
  "data": "this is a string",
  "error": {
    "123": "Something went wrong, fix it"
  }
}

这类似于我之前的问题,虽然在这种情况下'data'和'error'不包含集合。

例如,这个不工作…

public class ApiError
{
    int Number;
    string Message;
};
public class ApiResponse
{
    [JsonProperty(PropertyName = "status")]
    public string Status;
    [JsonProperty(PropertyName = "data")]
    public string Data;
    [JsonProperty(PropertyName = "error")]
    public ApiError Error;
};
var y = JsonConvert.DeserializeObject<ApiResponse>(SampleJson);
// y.Error.Number and y.Error.Message are both 0/null.

JSON with 'c#的子字段

c#中不能有以数字开头的字段/属性。所以在你的例子中,"error"的对象可以是一个Dictionary。所有JSON最终都只是键/值对。

[JsonProperty(PropertyName = "error")]
public Dictionary<int, string> Errors;