如何组合数据json?

时间:2018-04-14 05:14:00

标签: c# json

我有json数据

第一个数据:

"Data1":[
{"questionText":"Mudah 1",
"imageUrl":"Gambar1",
"answers":[
{"answerText":"A","isCorrect":true},
{"answerText":"B","isCorrect":false},
{"answerText":"C","isCorrect":false},
{"answerText":"D","isCorrect":false}]},

]

第二个数据:

"Data2":[
{"questionText":"Mudah 2",
"imageUrl":"Gambar2",
"answers":[
{"answerText":"A","isCorrect":true},
{"answerText":"B","isCorrect":false},
{"answerText":"C","isCorrect":false},
{"answerText":"D","isCorrect":false}]},

]

我想做什么

"DataCombine":[
{"questionText":"Mudah 1",
"imageUrl":"Gambar1",
"answers":[
{"answerText":"A","isCorrect":true},
{"answerText":"B","isCorrect":false},
{"answerText":"C","isCorrect":false},
{"answerText":"D","isCorrect":false}]},
{"questionText":"Mudah 2",
"imageUrl":"Gambar2",
"answers":[
{"answerText":"A","isCorrect":true},
{"answerText":"B","isCorrect":false},
{"answerText":"C","isCorrect":false},
{"answerText":"D","isCorrect":false}]},

]
我该怎么做才能合并这些数据?

1 个答案:

答案 0 :(得分:0)

假设你要这样做是C#那么基本上你的数据结构是相同的,但你的第一个JSON有1个条目,然后第二个也有一个条目你想要一个有2个条目的输出。

如果我还假设您的实际数据(我认为这不是您的真实数据,因为JSON实际上无效!)您拥有相同的数据结构名称,那么您可以执行以下操作。

首先定义你的类

public class Answer
{
    public string answerText { get; set; }
    public bool isCorrect { get; set; }
}

public class MyData
{
    public string questionText { get; set; }
    public string imageUrl { get; set; }
    public List<Answer> answers { get; set; }
}

public class RootObject
{
    public List<MyData> Data { get; set; }
}

现在您可以按照以下步骤进行反序列化,组合和序列化

string data1 = "{ \"Data\": [{   \"questionText\": \"Mudah 1\",   \"imageUrl\": \"Gambar1\",   \"answers\": [{     \"answerText\": \"A\",     \"isCorrect\": true    },    {     \"answerText\": \"B\",     \"isCorrect\": false    },    {     \"answerText\": \"C\",     \"isCorrect\": false    },    {     \"answerText\": \"D\",     \"isCorrect\": false    }   ]  } ]}";
string data2 = "{ \"Data\": [{  \"questionText\": \"Mudah 2\",  \"imageUrl\": \"Gambar2\",  \"answers\": [{    \"answerText\": \"A\",    \"isCorrect\": true   },   {    \"answerText\": \"B\",    \"isCorrect\": false   },   {    \"answerText\": \"C\",    \"isCorrect\": false   },   {    \"answerText\": \"D\",    \"isCorrect\": false   }  ] }]}";

RootObject d1 = JsonConvert.DeserializeObject<RootObject>(data1);
RootObject d2 = JsonConvert.DeserializeObject<RootObject>(data2);

d1.Data.AddRange(d2.Data);

string OutJson = JsonConvert.SerializeObject(d1);