2

I have this json file and i want to work with each object.

Json schema

So foreach is on way but tried many of them even from stack and it doesn't fetch these objects to i.

Any ideas what went wrong? I inspired by this thread

dynamic stuff = JsonConvert.DeserializeObject(File.ReadAllText(@"C:\Users\Paysami\Desktop\ccc\test.json"));
foreach (var i in stuff)
{
    //Console.WriteLine("{0} {1} {2} {3} {4} {5}\n", i.test1, i.test2, i.test3, i.test4, i.test5, i.test6);
    List<string> projectList = new List<string> { i.test1, i.test2, i.test3, i.test4, i.test5, i.test6 };
    foreach (var x in projectList)
    {
        Debug.WriteLine(x.ToString());
    }
}
Peter Csala
  • 17,736
  • 16
  • 35
  • 75
Paysami
  • 23
  • 4
  • 2
    Hi @Paysami, it would be great if you create [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) – Prasad Telkikar Aug 28 '20 at 13:44
  • 1
    Please do not share code via image. Please amend your question to include the sample json. Please also try to rephrase your problem / question. It's hard to understand what do you really want. – Peter Csala Aug 28 '20 at 14:08

3 Answers3

0

Your json doesn't contain any array and you can't use foreach to read that. You should first deserialize your json to a class and then use deserialized data.

public class Json
{
    public JsonObject Object1 { get; set; }

    public JsonObject Object2 { get; set; }

    public JsonObject Object3 { get; set; }
}

public class JsonObject
{
    public string Test1 { get; set; }
    public string Test2 { get; set; }
    public string Test3 { get; set; }
    public string Test4 { get; set; }
    public string Test5 { get; set; }
    public string Test6 { get; set; }
}

internal class Program
{
    private static void Main(string[] args)
    {
        var staff = JsonConvert.DeserializeObject<Json>(File.ReadAllText(@"jsonPath"));

        var jsonObjects = new List<JsonObject> { staff.Object1, staff.Object2, staff.Object3 };
        jsonObjects.ForEach(jsonObject => Console.WriteLine($"{jsonObject.Test1} {jsonObject.Test2}"));

        Console.ReadKey();
    }
}
0

You can also use First:

dynamic stuff = JsonConvert.DeserializeObject(File.ReadAllText(@"C:\.json"));
foreach (var i in stuff)
{
   List<string> projectList = new List<string> { (string)i.First.t1, (string)i.First.t2, (string)i.First.t3, (string)i.First.t4, (string)i.First.t5};
   foreach (var x in projectList)
   {
      Debug.WriteLine(x.ToString());
   }
}
Indycate
  • 11
  • 3
0

Create a model/dto class with properties match with JSON and do the serialize/deserialize based on your request so that your data will be parsed correctly.

Muni Chittem
  • 988
  • 9
  • 17