c#.json;我如何在这个文本文件中读取/修改/取出对象,并分离所有json格式的信息

本文关键字:json 对象 信息 格式 修改 分离 读取 文件 文本 | 更新日期: 2023-09-27 18:25:49

我有一个文本文件,其中包含json格式的文本,如下所示

[{"products":[{"product_id":"53743443003","quantity":4,"unit_price":42.71}],"value":170.84,"customer":{"id":58}},{"products":[{"product_id":"53743800103","quantity":8,"unit_price":36.78},{"product_id":"frontline-spot-on-Dog-3-1-10","quantity":4,"unit_price":24.62},{"product_id":"53743918500","quantity":7,"unit_price":18.44},{"product_id":"54993530183","quantity":1,"unit_price":57.44},{"product_id":"54993513347","quantity":10,"unit_price":5.0}],"value":629.24,"customer":{"id":18}},{"products":[{"product_id":"53743911105","quantity":8,"unit_price":22.97},{"product_id":"81572503779","quantity":8,"unit_price":63.0},{"product_id":"53743935308","quantity":1,"unit_price":61.96}],"value":749.72,"customer":{"id":53}}

很抱歉排长队,但你明白了。这个文本文件相当大,包含大约200个不同的"客户"

在c#中的控制台应用程序中工作时,我希望修改周围的数据,以便将其作为json文件输出到控制台中,和/或只能输出一种类型的对象,例如"product_id"。

products": [
    {
      "product_id": "53743800103",
      "quantity": 8,
      "unit_price": 36.78
    },
    {
      "product_id": "frontline-spot-on-Dog-3-1-10",
      "quantity": 4,
      "unit_price": 24.62
    },
    {
      "product_id": "53743918500",
      "quantity": 7,
      "unit_price": 18.44
    },
    {
      "product_id": "54993530183",
      "quantity": 1,
      "unit_price": 57.44
    },
    {
      "product_id": "54993513347",
      "quantity": 10,
      "unit_price": 5.0
    }
  ],
  "value": 629.24,
  "customer": {
    "id": 18
  }
}

我怎么能这么做?

c#.json;我如何在这个文本文件中读取/修改/取出对象,并分离所有json格式的信息

尝试一下:

string json = "[{"products":[{"product_id":"53743443003","quantity":4,"unit_price":42.71}],"value":170.84,"customer":{"id":58}},{"products":[{"product_id":"53743800103","quantity":8,"unit_price":36.78},{"product_id":"frontline-spot-on-Dog-3-1-10","quantity":4,"unit_price":24.62},{"product_id":"53743918500","quantity":7,"unit_price":18.44},{"product_id":"54993530183","quantity":1,"unit_price":57.44},{"product_id":"54993513347","quantity":10,"unit_price":5.0}],"value":629.24,"customer":{"id":18}},{"products":[{"product_id":"53743911105","quantity":8,"unit_price":22.97},{"product_id":"81572503779","quantity":8,"unit_price":63.0},{"product_id":"53743935308","quantity":1,"unit_price":61.96}],"value":749.72,"customer":{"id":53}}"
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter writer = new JsonTextWriter(sw))
{
    writer.Formatting = Formatting.Indented;
    writer.WriteRaw(json);
}
Console.WriteLine(sb.ToString());