Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize JSON array into string array

Say I have a string representing an array of objects in JSON form:

string s = "[{\"name\":\"Person1\"},{\"name\":\"Person2\"}]";

What I want is an array of strings, each string being the string representation of a JSON object - NOT the object itself. It should look something like this:

string[] s = new string[]
{
     "{\"name\":\"Person1\"}",
     "{\"name\":\"Person2\"}"
};

1) Almost every search I attempt pulls up millions of results on how to simply deserialize a JSON string using (eg) Json.NET. This is not what I want to do.

2) I have tried building a class representing the objects to temporarily loop through a deserialize/serialize mapping each to a string in an array, but the schema for the objects is variable (hence why I only need a string representation).

3) I have attempted a few regex to try and do this, but my JSON string can contain fields that contain JSON strings as their value (icky, but out of my control) and so nested character escaping etc drove me partially mad before I decided to beg for help here.

Surely this should be simple? Anybody got any pointers?

like image 862
Alex McMillan Avatar asked Feb 04 '16 04:02

Alex McMillan


2 Answers

You'll need to deserialize it, and then serialize each object independently. For example (using Newtonsoft.Json):

string json = "[{\"name\":\"Person1\"},{\"name\":\"Person2\"}]";

var objects = JsonConvert.DeserializeObject<List<object>>(json);
var result = objects.Select(obj => JsonConvert.SerializeObject(obj)).ToArray();

Yields (as a string[]):

{"name":"Person1"} 
{"name":"Person2"} 

If you try to avoid deserializing and serializing, you're almost certain to run into an edge case that will break your code.

like image 185
Rob Avatar answered Sep 19 '22 15:09

Rob


string s = "[{\"name\":\"Person1\"},{\"name\":\"Person2\"}]";
var Json = JsonConvert.DeserializeObject<List<object>>(s);
string[] Jsonn = Json.Select(x => x.ToString()).ToArray();

Response from [] Jsonn

[] Jsonn returns string array instead of object array with JObject formatted.

Hope this one help you.

like image 42
Krunal Mevada Avatar answered Sep 20 '22 15:09

Krunal Mevada