How to add jarray Object into JObject

前端 未结 4 1600
旧巷少年郎
旧巷少年郎 2021-02-05 03:07

How to add JArray into JObject? I am getting an exception when changing the jarrayObj into JObject.

paramete         


        
相关标签:
4条回答
  • 2021-02-05 03:33

    I see two problems with your code as you posted it.

    1. parameterNames needs to be an array of strings, not just a single string with commas.
    2. You can't add a JArray directly to a JObject; you have to put it in a JProperty and add that to the JObject, just like you are doing with the "birthday" and "email" properties.

    Corrected code:

    string[] parameterNames = new string[] { "Test1", "Test2", "Test3" };
    
    JArray jarrayObj = new JArray();
    
    foreach (string parameterName in parameterNames)
    {
        jarrayObj.Add(parameterName);
    }
    
    string txtBday = "2011-05-06";
    string txtemail = "dude@test.com";
    
    JObject UpdateAccProfile = new JObject(
                                   new JProperty("_delete", jarrayObj),
                                   new JProperty("birthday", txtBday),
                                   new JProperty("email", txtemail));
    
    Console.WriteLine(UpdateAccProfile.ToString());
    

    Output:

    {
      "_delete": [
        "Test1",
        "Test2",
        "Test3"
      ],
      "birthday": "2011-05-06",
      "email": "dude@test.com"
    }
    

    Also, for future reference, if you are getting an exception in your code, it is helpful if you say in your question exactly what the exception is, so that we don't have to guess. It makes it easier for us to help you.

    0 讨论(0)
  • 2021-02-05 03:36
    // array of animals
    var animals = new[] { "cat", "dog", "monkey" };
    
    // our profile object
    var jProfile = new JObject
            {
                { "birthday", "2011-05-06" },
                { "email", "dude@test.com" }
            };
    
    // Add the animals to the profile JObject
    jProfile.Add("animals", JArray.FromObject(animals));
    
    Console.Write(jProfile.ToString());
    

    Outputs:

    {    
      "birthday": "2011-05-06",
      "email": "dude@test.com",
      "animals": [
        "cat",
        "dog",
        "monkey"
      ]
    }
    
    0 讨论(0)
  • 2021-02-05 03:44
    var jObject = new JObject();
    jObject.Add("birthday", "2011-05-06");
    jObject.Add("email", "dude@test.com");
    var items = new [] { "Item1", "Item2", "Item3" };
    var jSonArray = JsonConvert.SerializeObject(items);
    var jArray = JArray.Parse(jSonArray);
    jObject.Add("_delete", jArray);
    
    0 讨论(0)
  • 2021-02-05 03:50

    it is easy,

    JArray myarray = new JArray();
    JObject myobj = new JObject();
    // myobj.add(myarray); -> this is wrong. you can not add directly.
    
    JProperty subdatalist = new JProperty("MySubData",myarray);
    myobj.Add(subdata); // this is the correct way I suggest.
    
    0 讨论(0)
提交回复
热议问题