-1

I have the below JSON content in a file.

[{
        "projectCode": "ICSM000003SM_Prj1",
        "name": "Story mapping",
        "id": "5eeb94710ce4e01aac9ac3e2",
        "workRequests": [{
                "name": "test issue",
                "project": "5eeb94710ce4e01aac9ac3e2",
                "id": "5eeb94930ce4e01aac9ac3ef",
                "url": "http://example.com/form?collectorid=5eeb94930ce4e01aac9ac3ef&icentid=5e8eff6b99ba793a08461372&projectid=5eeb94710ce4e01aac9ac3e2&source=mail"
            },
            {
                "name": "defect issue collector",
                "project": "5eeb94710ce4e01aac9ac3e2",
                "id": "5eee564170e0d814d0dd5288",
                "url": "http://example.com/form?collectorid=5eee564170e0d814d0dd5288&icentid=5e8eff6b99ba793a08461372&projectid=5eeb94710ce4e01aac9ac3e2&source=mail"
            }
        ]
    },
    {
        "projectCode": "ICSM000001IC100",
        "name": "issue collector",
        "id": "5e8eff7c99ba793a08461375",
        "workRequests": [{
                "name": "SE issue collector",
                "project": "5e8eff7c99ba793a08461375",
                "id": "5e96864599ba7923a488194a",
                "url": "http://example.com/form?collectorid=5e96864599ba7923a488194a&icentid=5e8eff6b99ba793a08461372&projectid=5e8eff7c99ba793a08461375&source=mail"
            },
            {
                "name": "test",
                "project": "5e8eff7c99ba793a08461375",
                "id": "5ee36aef1ad1de3c10fa9aa6",
                "url": "http://example.com/form?collectorid=5ee36aef1ad1de3c10fa9aa6&icentid=5e8eff6b99ba793a08461372&projectid=5e8eff7c99ba793a08461375&source=mail"
            }
        ]
    },
    {
        "projectCode": "ICSM000005SM_SP",
        "name": "Single project sm",
        "id": "5eee566970e0d814d0dd5289",
        "workRequests": [{
            "name": "feedback collector",
            "project": "5eee566970e0d814d0dd5289",
            "id": "5eee568c70e0d814d0dd5296",
            "url": "http://example.com/form?collectorid=5eee568c70e0d814d0dd5296&icentid=5e8eff6b99ba793a08461372&projectid=5eee566970e0d814d0dd5289&source=mail"
        }]
    }
]

Note: The above JSON content is dynamic. Its format is the same, but all values might change when I consume a REST API from the application.

Below is my code for converting JSON to treeview, but I want to display it in List or Details format.

public static void AddObjectNodes(JObject @object, string name, TreeNodeCollection parent)
    {
        var node = new TreeNode(name);
    //    if ()
        parent.Add(node);

        foreach (var property in @object.Properties())
        {
            AddTokenNodes(property.Value, property.Name, node.Nodes);
        }
    }
    private static void AddTokenNodes(JToken token, string name, TreeNodeCollection parent)
    {
        if (token is JValue)
        {
            parent.Add(new TreeNode(string.Format("{0}: {1}", name, ((JValue)token).Value)));
        }
        else if (token is JArray)
        {
            AddArrayNodes((JArray)token, name, parent);
        }
        else if (token is JObject)
        {
            AddObjectNodes((JObject)token, name, parent);
        }
    }
    private static void AddArrayNodes(JArray array, string name, TreeNodeCollection parent)
    {
        var node = new TreeNode(name);
        parent.Add(node);

        for (var i = 0; i < array.Count; i++)
        {
        AddTokenNodes(array[i], string.Format("[{0}]", i), node.Nodes);
        }
    }



var @object = JObject.Parse(json);
        AddObjectNodes(@object, "JSON", treeView.Nodes);

my problem is i am getting output like this

Enter image description here

I want the below list format. How do I handle JSON to get this data in C# Windows Forms?

I am using Newtonsoft Json.NET. Is there a way to break it into an arraylist?

---Work requestname ( Story mapping)
---Work requestname ( Story mapping)
---Work requestname ( Issue Collector)
---Work requestname ( Issue Collector)

And so on for a different work request

I am having a hard time generating a class for my JSON content. All online class generators generate a class for each project like I have project1, project2, and so on since my REST API will provide multiple projects and cannot create a class each time on the go.

This guy has his class sorted.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Dandy
  • 467
  • 1
  • 10
  • 33
  • 3
    Generally you want to avoid naming variables and parameters `object` or `array` as apart from running into _reserved word_ naming conflicts, such names aren't very informative –  Jun 22 '20 at 05:59
  • Dynamic means the format change. Changing value is a normal behavior. Why not having a list instead of an array list? [MSDN on don't use ArrayList](https://learn.microsoft.com/en-us/dotnet/api/system.collections.arraylist?view=netcore-3.1#remarks). And the whole code will just be a class definition and one line deserialization. – Drag and Drop Jun 22 '20 at 06:05
  • Does this answer your question? [Convert Json String to C# Object List](https://stackoverflow.com/questions/22191167/convert-json-string-to-c-sharp-object-list) – Drag and Drop Jun 22 '20 at 06:07
  • i am having hard time generating class for my json all online class generators generate class for each project like i have project1 , project2 & so on since my restapi will provide multiple projects cannot create class each time on the go – Dandy Jun 22 '20 at 06:16

2 Answers2

1

You can use Newtonsoft.Json.Linq to deserialize the original JSON content then deserialize your projects (with dynamic names I assume). You can go over each of the projects and display the ProjectObject that contains your names and URLs.

public class ProjectObject
{
    [JsonProperty("name")]
    public string Name { get; set; }
    [JsonProperty("url")]
    public string Url { get; set; }
}

And use the following in your main to deserialize JSON content and go over each project (project1, project2, projectn).

var jobj = JObject.Parse(json);
foreach(var prop in jobj.Properties())
{
    // prop.Name is the name of the project you are iterating over.
    var project = JsonConvert.DeserializeObject<List<ProjectObject>>(jobj[prop.Name].ToString());
}

UPDATED ANSWER

You can use the following classes to deserialize the new JSON content you posted.

public class Class1
{
    [JsonProperty("projectCode")]
    public string ProjectCode { get; set; }
    [JsonProperty("name")]
    public string Name { get; set; }
    [JsonProperty("id")]
    public string Id { get; set; }
    [JsonProperty("workRequests")]
    public List<Workrequest> WorkRequests { get; set; }
}

public class Workrequest
{
    [JsonProperty("name")]
    public string Name { get; set; }
    [JsonProperty("Pame")]
    public string Project { get; set; }
    [JsonProperty("id")]
    public string Id { get; set; }
    [JsonProperty("url")]
    public string Url { get; set; }
}

// And in your main, or other function, you can access your items via for loop or foreach. Ex to print all requests,
var obj = JsonConvert.DeserializeObject<List<Class1>>(json);
obj.ForEach(item => item.WorkRequests.ForEach(request => Console.WriteLine($"---Work {request.Name} ( {item.Name} )")));

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jawad
  • 11,028
  • 3
  • 24
  • 37
  • hi i am new to this json thing i have diffrent json now with actual data wil you help me generate and loop through it?? my expected output is same as mentioned in question just my json has been changed and this is the final one. i am updating json in Question – Dandy Jun 22 '20 at 07:38
  • i am able to parse my json in JArray – Dandy Jun 22 '20 at 07:50
  • @Dandy you changed the question altogether. This json doesnt have project1 project2 and so on. This new json has a standard format with different values of course. Not sure whats "dynamic" about it – Jawad Jun 22 '20 at 13:42
  • dude thanks a lot it worked,, about json i know, as soon as i got updated requirement i changed question but thanks again – Dandy Jun 22 '20 at 17:39
0
foreach (var property in @object.Properties())
{
     AddTokenNodes(property.Value, property.Name, node.Nodes);
}

Property.Name is the name of the property, not the value of the name attribute.

Try

AddTokenNodes(property.Value, property.Value.name, node.Nodes);

instead.

I am having a hard time generating a class for my JSON content. All online class generators generate a class for each project like I have project1, project2, and so on since my REST API will provide multiple projects and cannot create a class each time on the go.

You don’t need to create a new class every time. that's what the dynamic Newtonsoft JSON classes are for.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Joshua H
  • 75
  • 1
  • 9