Click here to Skip to main content
15,879,683 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
Hello, currently I am working on WinForms application that has been communicating with API which is based on websocket as a transport protocol where each message is json encoded object. I want to loop through each array in params JArray, take values of every name field, and store these all values in one list. So here is what I have tried:

What I have tried:

1. here is the response message from server as a string:
C#
string receivedResult = "{\"method\":\"_result\",\"params\":[[{\"idmake\":1,\"name\":\"Abarth\",\"important\":0,\"description\":{\"DE\":\"Abarth & C. S.p.A., Corso Giovanni Agnelli 200, I – 10135 Torino, Italia.\\nwww.abarth.it\\nGegründet 1949 von Carlo Abarth. Seit 2007 Teil von Fiat zur Produktion und Vertrieb von sportlichen Versionen von Fiat-Modellen.\",\"EN\":\"Abarth & C. S.p.A., Corso Giovanni Agnelli 200, I – 10135 Torino, Italy.\\nwww.abarth.it\",\"ES\":\"Abarth & C. S.p.A., Corso Giovanni Agnelli 200, I – 10135 Torino, Italia.\\nwww.abarth.it\",\"FR\":\"Abarth & C. S.p.A., Corso Giovanni Agnelli 200, I – 10135 Torino, Italie.\\nwww.abarth.it\",\"PO\":\"Abarth & C. S.p.A., Corso Giovanni Agnelli 200, I – 10135 Torino, Itàlia.\\nwww.abarth.it\"},\"doneyears\":[[1955,1961],[1963,1971],[2008,2020]]},{\"idmake\":2,\"name\":\"AC\",\"important\":0,\"description\":{\"DE\":\"AC Cars, Siemensstrasse, 75334 Straubenhart, Deutschland.\\nwww.ac-automotive.com\\nGegründet 1911 in Grossbritannien. Fertigung des Mk VI heute in Heya, Deutschland.\",\"EN\":\"AC Cars, Siemensstrasse, 75334 Straubenhart, Germany.\\nwww.ac-automotive.com\",\"ES\":\"AC Cars, Siemensstrasse, 75334 Straubenhart, Alemania.\\nwww.ac-automotive.com\",\"FR\":\"AC Cars, Siemensstrasse, 75334 Straubenhart, Allemagne.\\nwww.ac-automotive.com\\nCréée en 1911, en Grande Bretagne. Fabrication de la Mk VI aujourd'hui à Heya, Allemagne.\",\"PO\":\"AC Cars, Siemensstrasse, 75334 Straubenhart, Alemanha.\\nwww.ac-automotive.com\"},\"doneyears\":[[1948,1963],[1966,1991],[1993,1996],[2000,2003],[2007,2008],[2010,2019]]},{\"idmake\":3,\"name\":\"Acura\",\"important\":0,\"description\":{\"DE\":\"Acura Division, American Honda Motor Co., Inc., 1919 Torrance Boulevard, Torrance, California 90 501.2746, USA.\\nwww.acura.com\\nSeit 1986 als Premium-Marke von Honda auf dem amerikanischen Markt mit eigenständigen Modellen.\",\"EN\":\"Acura Division, American Honda Motor Co., Inc., 1919 Torrance Boulevard, Torrance, California 90 501.2746, USA.\\nwww.acura.com\",\"ES\":\"Acura Division, American Honda Motor Co., Inc., 1919 Torrance Boulevard, Torrance, California 90 501.2746, EE. UU.\\nwww.acura.com\",\"FR\":\"Acura Division, American Honda Motor Co., Inc., 1919 Torrance Boulevard, Torrance, California 90 501.2746, USA.\\nwww.acura.com\\nDepuis 1986, marque haut de gamme de Honda sur le marché américain, avec ses propres modèles.\",\"PO\":\"Acura Division, American Honda Motor Co., Inc., 1919 Torrance Boulevard, Torrance, California 90 501.2746, EUA.\\nwww.acura.com\",\"RU\":null},\"doneyears\":[[1966,1966],[1988,1988],[1991,1991],[1996,2003],[2007,2020]]}";

2.Next thing that I've done is parsing this string to be JObject by following statement:
C#
var jObject = JObject.Parse(receivedResult);

3. After parsing I am getting following formatted output:
C#
{
  "method": "_result",
  "params": [
    [
      {
        "idmake": 1,
        "name": "Abarth",
        "important": 0,
        "description": {
          "DE": "Abarth & C. S.p.A., Corso Giovanni Agnelli 200, I – 10135 Torino, Italia.\nwww.abarth.it\nGegründet 1949 von Carlo Abarth. Seit 2007 Teil von Fiat zur Produktion und Vertrieb von sportlichen Versionen von Fiat-Modellen.",
          "EN": "Abarth & C. S.p.A., Corso Giovanni Agnelli 200, I – 10135 Torino, Italy.\nwww.abarth.it",
          "ES": "Abarth & C. S.p.A., Corso Giovanni Agnelli 200, I – 10135 Torino, Italia.\nwww.abarth.it",
          "FR": "Abarth & C. S.p.A., Corso Giovanni Agnelli 200, I – 10135 Torino, Italie.\nwww.abarth.it",
          "PO": "Abarth & C. S.p.A., Corso Giovanni Agnelli 200, I – 10135 Torino, Itàlia.\nwww.abarth.it"
        },
        "doneyears": [
          [
            1955,
            1961
          ],
          [
            1963,
            1971
          ],
          [
            2008,
            2020
          ]
        ]
      },
      {
        "idmake": 2,
        "name": "AC",
        "important": 0,
        "description": {
          "DE": "AC Cars, Siemensstrasse, 75334 Straubenhart, Deutschland.\nwww.ac-automotive.com\nGegründet 1911 in Grossbritannien. Fertigung des Mk VI heute in Heya, Deutschland.",
          "EN": "AC Cars, Siemensstrasse, 75334 Straubenhart, Germany.\nwww.ac-automotive.com",
          "ES": "AC Cars, Siemensstrasse, 75334 Straubenhart, Alemania.\nwww.ac-automotive.com",
          "FR": "AC Cars, Siemensstrasse, 75334 Straubenhart, Allemagne.\nwww.ac-automotive.com\nCréée en 1911, en Grande Bretagne. Fabrication de la Mk VI aujourd'hui à Heya, Allemagne.",
          "PO": "AC Cars, Siemensstrasse, 75334 Straubenhart, Alemanha.\nwww.ac-automotive.com"
        },
        "doneyears": [
          [
            1948,
            1963
          ],
          [
            1966,
            1991
          ],
          [
            1993,
            1996
          ],
          [
            2000,
            2003
          ],
          [
            2007,
            2008
          ],
          [
            2010,
            2019
          ]
        ]
      },
      {
        "idmake": 3,
        "name": "Acura",
        "important": 0,
        "description": {
          "DE": "Acura Division, American Honda Motor Co., Inc., 1919 Torrance Boulevard, Torrance, California 90 501.2746, USA.\nwww.acura.com\nSeit 1986 als Premium-Marke von Honda auf dem amerikanischen Markt mit eigenständigen Modellen.",
          "EN": "Acura Division, American Honda Motor Co., Inc., 1919 Torrance Boulevard, Torrance, California 90 501.2746, USA.\nwww.acura.com",
          "ES": "Acura Division, American Honda Motor Co., Inc., 1919 Torrance Boulevard, Torrance, California 90 501.2746, EE. UU.\nwww.acura.com",
          "FR": "Acura Division, American Honda Motor Co., Inc., 1919 Torrance Boulevard, Torrance, California 90 501.2746, USA.\nwww.acura.com\nDepuis 1986, marque haut de gamme de Honda sur le marché américain, avec ses propres modèles.",
          "PO": "Acura Division, American Honda Motor Co., Inc., 1919 Torrance Boulevard, Torrance, California 90 501.2746, EUA.\nwww.acura.com",
          "RU": null
        },
        "doneyears": [
          [
            1966,
            1966
          ],
          [
            1988,
            1988
          ],
          [
            1991,
            1991
          ],
          [
            1996,
            2003
          ],
          [
            2007,
            2020
          ]
        ]
      }
    ]
  ],
  "seq": 100
}

I want to take every value of field name in arrays, and store these all values in list, I was able to take the name value from the first array which is Abarth by the following code:
C#
JArray paramsArray = (JArray)jObject["params"];
            List<string> listName = new List<string>();

            foreach(JToken param in paramsArray)
            {
                name = (string)param[0]["name"]; // Here I got the target result name="Abarth" from index 0 of array
                listName.Add(name);

                foreach(var item in listName)
                {
                    tbResultCreateNewAd.Text = item.ToString();
                }
                
            }

I was wondering how can I loop through other arrays and take name values?
Posted
Updated 12-Jan-23 6:43am
Comments
Graeme_Grant 4-Jul-22 10:32am    
Do you require the rest of the JSON data?
Jakobson 2022 4-Jul-22 11:12am    
No, just only name and idmake, but I figured out how to do this. Maybe there is something different but this works for me, I will add solution
[no name] 4-Jul-22 10:54am    
The foreach "within" foreach doesn't makes sense; in the present context, the second foreach should come after the first. And to "concatenate" to .Text, use "+=", not just "=".
Jakobson 2022 4-Jul-22 11:12am    
Agree with you, I figured out how to solve this, thank you

Here is how to pull the doneyears:
C#
//List<string> listName = new List<string>();
Dictionary<string, Dictionary<int, int>> map
    = new Dictionary<string, Dictionary<int, int>>();

foreach(JToken param in paramsArray)
{
    string name = (string)param[0]["name"];

    Dictionary<int, int> tokens = new Dictionary<int, int>();

    foreach (JToken token in param[0]["doneyears"])
        tokens.Add((int)token.First(), (int)token.Last());

    map.Add(name, tokens);
}
 
Share this answer
 
Comments
Jakobson 2022 4-Jul-22 11:18am    
Actually, far better then my hardcoded value and while loop, that is what I have looking for thank you bro
Graeme_Grant 4-Jul-22 11:20am    
no problems ... of course you will need to iterate through all of the params but there is enough here to point you in the right direction.
I've found out how can be done after spending a while, through the while loop I hardcoded the last index number of child arrays, and then do the iteration over all, maybe there exists different solution for this, but for now this logic for me works, combobox is filling after click event is fired properly.

 var jObject = JObject.Parse(receivedResult);
                JArray paramsArray = (JArray)jObject["params"];
                foreach(JToken param in paramsArray)
                {
                    int i = 0;
                    while(i<614) // 614 is hardcoded number for last array index
                    { 
                        name = param[i]["name"].ToString();
                        listName.Add(name);
                        i++;
                       
                    }
                    break;
                }
cbMake.DataSource = listName;
 
Share this answer
 
Comments
Richard MacCutchan 4-Jul-22 11:31am    
Don't hard code values like that, use param.length.
Jakobson 2022 4-Jul-22 11:36am    
thank you, I know that is bad practice to hard code the values, I will do it as you said
The paramsArray variable is an array of arrays, not an array of JSON objects. So you probably need something like:
Java
JArray paramsArray = (JArray)jObject["params"];
List<string> listName = new List<string>();

foreach(JToken param in paramsArray)
{
    foreach(JToken item in param) {
        name = (string)item["name"];
        listName.Add(name);
    }
}

// This loop needs to run after the previous two. But why do you need it at all, when you can add the names in the inner of the above two loops?
    foreach(var item in listName)
    {
        tbResultCreateNewAd.Text += item.ToString();
    }
    
}
 
Share this answer
 
Comments
Jakobson 2022 4-Jul-22 11:26am    
Yes you are right, that is array of arrays, I am new to working with Json, last foreach loop for writing values to the textboxes was there in purpose of testing.. I deleted that
Step 1: 

   dynamic response = JsonConvert.DeserializeObject(json);

Step 2: 

     JArray paramsArray = (JArray)JToken.FromObject(response);

Step 3: 

     foreach (JToken param in paramsArray)
                {
          CustomerRoot objCustomerRoot = param.ToObject<CustomerRoot>(); // Customer Root is class
         string CustomerID = objCustomerRoot.CustomerID.tostring();
                }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900