我有以下格式的JSON
{
"results":
[
{
"position": {"Field1":11,"Filed2":12},
"Field3":13,
"Filed4":14,
"Field5":15
},
{
"position":{"Field1":21,"Filed2":22},
"Field3":23,
"Filed4":24,
"Filed5":25
}
]
}
转换为以下格式
{
"results":
[
{
"Field1":11,
"Filed2":12,
"Field3":13,
"Filed4":14,
"Field5":15
},
{
"Field1":21,
"Filed2":22,
"Field3":23,
"Filed4":24,
"Filed5":25
}
]
}
我正在尝试下面的代码有没有更好的方法来处理这个
for(int i = 0; i<resultsJSONArray.length(); ++i){
if(resultsJSONArray.get(i).has("position")) {
String names[] = JSONObject.getNames(resultsJSONArray.get(i).get("position")));
for(int i = 0; i<names().length; ++i) {
resultsJSONArray.get(i).put(names[i],resultsJSONArray.get(i).get("position").get(names[i]));
}
JSONObject.getNames(resultsJSONArray.get(i).remove("position"));
}
}
答案 0 :(得分:0)
class SourceJSON{
// define data model for original json format
}
class DestJSON{
// define data model for required json format
}
//最后你可以将原始源转换为数据类,格式化并写回json格式
SourceJSON data = new Gson().fromJson(json, SourceJSON.class);
DestJSON destdata = new DestJSON();
destdata.setField(data.get(..));
Gson gson = new Gson();
String json = gson.toJson(destdata);