0
{"data": [
  {
     "id": "X12",
     "from": {
        "name": "test1", "id": "1458633"
     }
  },
  {
     "id": "X45",
     "from": {
        "name": "test2", "id": "12587521"
     }

  },
  {
     "id": "X46",
     "from": {
        "name": "test3", "id": "12587521"
     }

  }

I want to swap the array index of the json file using C#. Ex. data[2] swap with data[3] ->

{"data": [
  {
     "id": "X46",
     "from": {
        "name": "test3", "id": "12587521"
     }

  },
  {
     "id": "X45",
     "from": {
        "name": "test2", "id": "12587521"
     }

  }

Are there anyway to do this without creating many temp variables?

Selim Yildiz
  • 5,254
  • 6
  • 18
  • 28
cphant
  • 1

2 Answers2

1

You can use this extension method with using JArray

public static void SwapValues(this JArray source, Int32 index1, Int32 index2)
{
    JToken temp = source[index1];
    source[index1] = source[index2];
    source[index2] = temp;
}

Then implementation just like this:

JArray jsonArray = JArray.Parse(json);
jsonArray.SwapValues(2, 1);
Selim Yildiz
  • 5,254
  • 6
  • 18
  • 28
  • The approach that @SelimYıldız shared can help swap two array items, why got a votedown without any useful comment. – Fei Han Jan 01 '20 at 06:11
0

I want to swap the array index of the json file using C#. Ex. data[2] swap with data[3]

You can try the following approach to achieve the requirement.

JObject myobj = JObject.Parse(jdata);

//add the second item of array after the third item

((JArray)myobj["data"])[2].AddAfterSelf(((JArray)myobj["data"])[1]);

//then remove the second item
((JArray)myobj["data"])[1].Remove();

//and now, data[2] swap with data[3]

Test Result

enter image description here

Fei Han
  • 26,415
  • 1
  • 30
  • 41