{"data": [
{
"id": "X12",
"from": {
"name": "test1", "id": "1458633"
}
},
{
"id": "X45",
"from": {
"name": "test2", "id": "12587521"
}
},
{
"id": "X46",
"from": {
"name": "test3", "id": "12587521"
}
}
我想使用C#交换json文件的数组索引。例如数据[2]与数据[3]交换->
{"data": [
{
"id": "X46",
"from": {
"name": "test3", "id": "12587521"
}
},
{
"id": "X45",
"from": {
"name": "test2", "id": "12587521"
}
}
有没有做任何不创建许多临时变量的事情?
答案 0 :(得分:0)
我想使用C#交换json文件的数组索引。例如数据[2]与数据[3]交换
您可以尝试以下方法来达到要求。
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]
测试结果
答案 1 :(得分:-1)
您可以通过JArray
public static void SwapValues(this JArray source, Int32 index1, Int32 index2)
{
JToken temp = source[index1];
source[index1] = source[index2];
source[index2] = temp;
}
然后像这样实现:
JArray jsonArray = JArray.Parse(json);
jsonArray.SwapValues(2, 1);