【问题标题】:how to deserialize a custom json to c# object如何将自定义 json 反序列化为 c# 对象
【发布时间】:2021-07-09 08:31:28
【问题描述】:

我使用 Newtonsoft.json 来反序列化这个 json

{
    "pdf_info": [
        [
         -> this is a object {
           "order_serial_no": "xxxxx",
           // more properties
         },
        -> this is an array ["xxxx", "x"]
        ]
    ]
}

在java中我可以使用下面的代码来实现。

JSONArray pdfArray = JSONArray.parseArray(pdf_info);
String pdfArrayOne = pdfArray.getString(0);
JSONArray jsonArray = JSONObject.parseObject(pdfArrayOne, JSONArray.class);
String jsonData = jsonArray.getString(0);
Pdf pdf = JSONObject.parseObject(jsonData, Pdf.class);

那么,如何用 newtonsoft.json 反序列化这个 json

【问题讨论】:

  • 那不是有效的 JSON,所以你不能。
  • @Llama 我认为'-> this is an...' 字符串应该是 cmets,而不是 json 的实际内容... :)

标签: java c# json json.net


【解决方案1】:

显然(在删除你的 cmets 之后)这将是你的对象的 c# 类 (将 json 复制到剪贴板 -> 在 Visual Studio 中“编辑 -> 粘贴特殊 -> 将 json 粘贴为类” - see more on this

public class Rootobject
{
  public object[][] pdf_info { get; set; }
}

定义此类型,您将能够使用以下方法对其进行反序列化:

Newtonsoft.Json.JsonConvert.DeserializeObject<Rootobject>(System.IO.File.ReadAllText(fileName));

【讨论】:

    【解决方案2】:

    首先 -> 阅读文档。
    其次:
    JObject data = JObject.Parse(jsonText); // deserialize to dict-like object

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-19
      • 2022-11-15
      • 2020-07-19
      • 2021-06-24
      • 1970-01-01
      相关资源
      最近更新 更多