Home > Enterprise >  How to decompose a string containing a json array in C sharp
How to decompose a string containing a json array in C sharp

Time:09-22

In C sharp, may I ask how to decompose a string containing a json array into an array with each element as a json string? Thanks!

One example of the string is as following.

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"}]"

I want to get an array as below.

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

I tried to use JsonConvert.DeserializeObject(string), but it does not work with error Unexpected character encountered while parsing value: [.

Thanks!

CodePudding user response:

is this what you want?

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

output:

{"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"}

CodePudding user response:

One of the reasons for the error may be that you are using different names for the objects in the json text. For example: value and value_2

if the value is more than one and dynamic then it is more convenient to specify it in an array. like this.

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

for this you need to edit the json text then adapt the object to it.

give this a try

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

Converts the given Json text to the object you give. If Json and object are different it will throw an error . look here

thank you USEFUL for feedback if it worked for you

  • Related