Home > Enterprise >  How would you add all elements of a JArray to a JObject in C#?
How would you add all elements of a JArray to a JObject in C#?

Time:11-05

I am trying to add the elements of a JArray to a JObject in C#. I have the solution in Java, but cannot figure out how to do the same in C#. Here is my Java code:

 public static JSONObject[] fetchData(String dataFile, String arrayName) {
    JSONArray jsonArray;
    try {
        jsonArray = extractObject_JSON(dataFile).getJSONArray(arrayName);
    } catch (Exception e) {
        // If Method Name is not matching with arrayName, then default will be taken
        jsonArray = extractObject_JSON(dataFile).getJSONArray("default");
    }
    JSONObject[] jsonObject = new JSONObject[jsonArray.length()];
    for (int i = 0; i < jsonArray.length(); i  ) {
        jsonObject[i] = jsonArray.getJSONObject(i);
    }
    return jsonObject;
}

and here is my C# code:

public static JObject FetchData(string testMethodName)
{

    using (StreamReader r = new StreamReader("PathToFile"))
    {
        string jsonstring = r.ReadToEnd();
        JObject obj = JObject.Parse(jsonstring);
        JArray jsonArray = JArray.Parse(obj[testMethodName].ToString());

        JObject jObject = new JObject();
        for (int i = 0; i < jsonArray.Count; i  )
        {
            jObject[i] = jsonArray[i];

        }

        return jObject;
    }

}

jsonArray in this code example returns:

{[
  {
    "loginId": "testuser1",
    "userCase": "verify for user"
  },
  {
    "loginId": "testuser2",
    "userCase": "verify for user"
  }
]}

The testMethodName would be LoginTest_E2E (see .json input file below)

   {
      "LoginTest_E2E": [
        {
          "loginId": "testuser1",
          "userCase": "verify for user"
        },
        {
          "loginId": "testuser2",
          "userCase": "verify for user"
        }
      ]
    }

When I run my C# code I get the following error:

System.ArgumentException: 'Set JObject values with invalid key value: 0. Object property name expected.'

I would like the fetchData method to return a JObject of:

 { 
    "loginId": "testuser1",
    "userCase": "verify for user"
  },
  {
    "loginId": "testuser2",
    "userCase": "verify for user"
  }

Does anyone know how to solve this in C#?

CodePudding user response:

As you have it written, jObject is expecting a string value for the key of the property you are adding to it. At least that's my understanding judging from the fact that JObject extends IDictionary<string, JToken>: https://www.newtonsoft.com/json/help/html/t_newtonsoft_json_linq_jobject.htm

You're trying to give it an integer value as a key. Judging from your Java code, it looks like you meant to declare an array of JObjects, but you just declared one here:

JObject jObject = new JObject();

If this is the case, change it to JObject[] as @Selman said.

CodePudding user response:

There are two different types JArray and JObject. You can not just return array as JObject. You can return or JArray or JObject[]. And don't be confused. JObject[] is not a Json array, it is a C# array of Json objects.

public static JObject[] FetchData(string testMethodName, string pathToFile)
{

    string json = string.Empty;
    using (StreamReader r = new StreamReader(@pathToFile))
        json = r.ReadToEnd();
    JObject obj = JObject.Parse(json);
    JArray jsonArray = JArray.Parse(obj[testMethodName].ToString());

    JObject[] jObjects = new JObject[jsonArray.Count];
    for (int i = 0; i < jsonArray.Count; i  )
        jObjects[i] = JObject.Parse(jsonArray[i].ToString());

    return jObjects;
}

or using linq

public static JObject[] FetchData(string testMethodName, string filePath)
{
    string json = string.Empty;
    using (StreamReader r = new StreamReader(@fileToPath))
        json = r.ReadToEnd();
    JObject obj = JObject.Parse(json);
   var ja= JArray.Parse( obj[testMethodName].ToString() );
    return  ja.Select(j => JObject.Parse(j.ToString()) ).ToArray();
}

output

[
{ 
    "loginId": "testuser1",
    "userCase": "verify for user"
  },
  {
    "loginId": "testuser2",
    "userCase": "verify for user"
  }
]
  • Related