0

I have a array of string. I want to make a JSON file from it, mapping it to a hierarchy of nested objects using the strings as property names and final value. For example, if array contains {"A", "B", "C", "D"}, then the resultant JSON file should look like

{
  "A": {
    "B": {
      "C": "D"
       }
    }
}

Is there any way to do that?

6
  • 4
    Yes, there are many ways to do that. Commented Sep 30, 2019 at 6:33
  • You can achieve this by contacting string after that user serialize and deserialize. Commented Sep 30, 2019 at 6:37
  • 2
    Although this is possible, it surprises me this is needed anywhere... Though questions on stackoverflow surprise me a lot Commented Sep 30, 2019 at 6:41
  • 1
    The rule for converting from strings to JSON isn't entirely clear. Is this what you want? dotnetfiddle.net/DKaAoH Commented Sep 30, 2019 at 6:55
  • 2
    Thanks @dbc for your reference. That worked !! Commented Sep 30, 2019 at 8:39

1 Answer 1

2

You can generate a nested set of JSON objects from an array of strings using LINQ and a JSON serializer (either or ) as follows:

var input = new[]{"A","B","C","D"};

var data = input
    .Reverse()
    .Aggregate((object)null, (a, s) => a == null ? (object)s : new Dictionary<string, object>{ { s, a } });

var json = JsonConvert.SerializeObject(data, Formatting.Indented);

The algorithm works by walking the incoming sequence of strings in reverse, returning the string itself for the last item, and returning a dictionary with an entry keyed by the current item and valued by the previously returned object for subsequent items. The returned dictionary or string subsequently can be serialized to produce the desired result.

Demo fiddle here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.