如何在 C sharp 中分解包含 json 数组的字符串

How to decompose a string containing a json array in C sharp

在C sharp中,请问如何将包含json数组的字符串分解为每个元素为json字符串的数组?谢谢!

字符串示例如下

var string = "[{"id": 111, "value": 22, "timestamp": "2021-09-20T02:34:17.000Z"},{"id": 112, "value_1": 23, "value_2": 24, "timestamp": "2021-09-20T02:33:17.000Z"}]"

我想得到如下数组。

var messages = new[]
{
@"{'id': 111, 'value': 22, 'timestamp': '2021-09-20T02:34:17.000Z'}",
@"{'id': 112, 'value_1': 23, 'value_2' : 24, 'timestamp': '2021-09-20T02:33:17.000Z'}"
}.AsEnumerable();

我尝试使用 JsonConvert.DeserializeObject(string),但它不起作用并出现错误 Unexpected character encountered while parsing value: [

谢谢!

错误的原因之一可能是您对 json 文本中的对象使用了不同的名称。例如:valuevalue_2

如果值大于一并且是动态的,那么在数组中指定它会更方便。像这样。

{'id': 112, ['value_1': 23, 'value_2' : 24], 'timestamp': '2021-09-20T02:33:17.000Z'}

为此,您需要编辑 json 文本,然后使对象适应它。

试试这个

JsonConvert.DeserializeObject<MyObject>("//Your Json string");

将给定的 Json 文本转换为您提供的对象。如果 Json 和 object 不同,它将抛出错误。 look here

感谢您的反馈,如果它对您有用

这是你想要的吗?

using System;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

string input = "[{\"id\": 111, \"value\": 22, \"timestamp\": \"2021 - 09 - 20T02: 34:17.000Z\"},{\"id\": 112, \"value_1\": 23, \"value_2\": 24, \"timestamp\": \"2021 - 09 - 20T02: 33:17.000Z\"}]";

// Read Json into JArray
JArray array = JArray.Parse(input);

// Serialize each nested object into string Array
string[] output = array.Select((a) => JsonConvert.SerializeObject(a)).ToArray();


foreach (string line in output)
    Console.WriteLine(line);

输出:

{"id":111,"value":22,"timestamp":"2021 - 09 - 20T02: 34:17.000Z"}
{"id":112,"value_1":23,"value_2":24,"timestamp":"2021 - 09 - 20T02: 33:17.000Z"}