简体   繁体   中英

How would you add a JArray into a JObject without adding a new JObject key/name?

using .NET C#, I am trying to create a new JObject from a JArray. I have a FetchData JObject that I want to return a JObject of data for data driven testing. Here is what I have so far:

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

                JObject jObject = new JObject(new JProperty("test",jsonArray));

                return jObject;
            }

        }

I want to return a JObject of test data that pertains to the testMethod which is being run. when I run this code, jObject returns:

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

My issue is that I only want to return the following arrays within the JObject:

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

I have researched for a while and cannot find a solution without adding a key to the new JObject, in this case, key being "test".

Is this even possible in C#?

I have also tried adding the JArray directly to the JObject:

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

but get error : System.ArgumentException: 'Can not add Newtonsoft.Json.Linq.JArray to Newtonsoft.json.Linq.JObject

I have also tried adding the arrays to the JObject like this:

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

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

fwiw this is how I am doing this is Java and it works like a charm, but I cannot figure it out in C#. Java Code:

JSONObject[] jsonObject = new JSONObject[jsonArray.length()];
        for (int i = 0; i < jsonArray.length(); i++) {
            jsonObject[i] = jsonArray.getJSONObject(i);
        }

To get first element of array you can do next:

var json = @"{
""test"": [
    {
      ""loginId"": ""testuser1"",
      ""userCase"": ""verify for user""
    },
    {
      ""loginId"": ""testuser2"",
      ""userCase"": ""verify for user""
    }]
}";
var testMethodName = "test";
var jObject = JObject.Parse(json);
var first = (JObject)jObject[testMethodName][0]; // note that this can throw for multiple reasons

Analog of your java code would be:

// parse jObject as earlier
var jArr = (JArray)jObject[testMethodName];
var jsonObjectArr = new JObject[jArr.Count];
for (int i = 0; i < jArr.Count; i++)
{
    jsonObjectArr[i] = (JObject)jArr[i];
}

Or you can use LINQ to JSON :

// parse jObject as earlier
var jsonObjectArr = jObject[testMethodName]
    .Children<JObject>()
    .ToArray();

Why don't you return only the first object of your array like this:

public static JToken FetchOneDatum(string testMethodName)
{
  string jsonString = GetFileContent("sampleTest.txt");
  JObject obj = JObject.Parse(jsonString);
  JArray jsonArray = JArray.Parse(obj[testMethodName].ToString());
  return jsonArray[0];
}

You can find the whole visual Studio solution here: solution on GitHub

C# approach ;)

public class Test
{
    public string loginId { get; set; }
    public string userCase { get; set; }
}

public class Scenario
{
    public Test[] tests { get; set; }
}

// Usage
public static Test FetchData(string testMethodName)
{
    using (var reader = new StreamReader("PathToJsonfile"))
    {
        var json = reader.ReadToEnd();
        var scenario = JsonConvert.DeserializeObject<Scenario>(json);

        return scenario.tests.First();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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