3

I'm trying to create named JArrays using JSON.net. I have a list of food, like Milk in the example below.

On initial writing of this data, all food items in the List (say List()) have an array created for each food item, as child arrays in the Items array.

Then later on, when adding a food JObject, I add it to the appropriate sub-array.

The problem is creating the sub-arrays for each item in my list. Maybe it's due to it being 5am, but I just can't seem to figure it out.

PS: I know I could create an example class like the Items class below, however.. I'm trying to do this dynamically. I have a list of data that I can pull the entire food list from (in string format), so it would save hours of tedium if I could do this via the List I have for the food items.

Any help is appreciated. Thank you

class Items{
    public List<string> Milk {get; set;}
    public List<string> Bread {get; set;}
}


    // Example Json
    {
    "Items":[
        "Milk":
        [
            {
                "name": "old milk",
            }
        ]
    ]
}
2
  • 1
    how about using JSON.Stringify on a dynamic object that you create Commented Feb 24, 2017 at 5:14
  • 1
    That worked perfectly. I knew it was the late night programming to blame :( Can you make your comment into an answer so I can mark it as accepted? Thanks! Commented Feb 24, 2017 at 5:17

1 Answer 1

1

you have the instance of items class here:

Items items = new Items();

Instantiate a new list for milk:

List<string> Milk = new List<string>();

Add items to the list of Milk string:

Milk.Add("old milk");

Copy the List to items.Milk :

items.Milk = Milk;

And convert items object into a Json String:

var JsonItems = JSON.Stringify(items);

this is just the implementation of the class in your example.

A better option would be to use the Dictionary object for milk and bread

ie., it looks something like milk<"name", "Old milk">

Hope this helps.

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.