简体   繁体   English

如何将 JArray 的所有元素添加到 C# 中的 JObject?

[英]How would you add all elements of a JArray to a JObject in C#?

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:我正在尝试将JArray的元素添加到JObject中的 JObject。我在 Java 中有解决方案,但无法弄清楚如何在 C# 中执行相同的操作。这是我的 Java 代码:

 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:这是我的 C# 代码:

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:此代码示例中的jsonArray返回:

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

The testMethodName would be LoginTest_E2E (see.json input file below) testMethodName将是 LoginTest_E2E(请参阅下面的 json 输入文件)

   {
      "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:当我运行 C# 代码时,出现以下错误:

System.ArgumentException: 'Set JObject values with invalid key value: 0. Object property name expected.' System.ArgumentException:“使用无效键值设置 JObject 值:0。应为 Object 属性名称。”

I would like the fetchData method to return a JObject of:我希望fetchData方法返回一个JObject

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

Does anyone know how to solve this in C#? C#有人知道怎么解决吗?

As you have it written, jObject is expecting a string value for the key of the property you are adding to it.正如您所写的那样,jObject 期望您添加到它的属性的键的字符串值。 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至少从 JObject 扩展 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:从您的 Java 代码来看,您似乎打算声明一个 JObject 数组,但您只是在此处声明了一个:

JObject jObject = new JObject(); JObject jObject = new JObject();

If this is the case, change it to JObject[] as @Selman said.如果是这种情况,请按照@Selman 所说将其更改为 JObject[]。

There are two different types JArray and JObject.有两种不同的类型 JArray 和 JObject。 You can not just return array as JObject.您不能只将数组作为 JObject 返回。 You can return or JArray or JObject[].您可以返回或 JArray 或 JObject[]。 And don't be confused.不要混淆。 JObject[] is not a Json array, it is a C# array of Json objects. JObject[] 不是 Json 数组,它是 Json 对象的 C# 数组。

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或使用 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"
  }
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM