Deserialize JSON array into string array

18,300

Solution 1

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.

Solution 2

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.

Share:
18,300
Alex McMillan
Author by

Alex McMillan

This page intentionally left blank.

Updated on August 07, 2022

Comments

  • Alex McMillan
    Alex McMillan over 1 year

    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?