我有以下代码来解析一些 JSON:
public void parseAvatar() throws IOException, JSONException{
is.readInt();
jo.put("currentHomeId", is.readLong());
jo.put("homeId", is.readLong());
byte isInClan = is.readByte();
if (isInClan == 1) {
jo.put("clanId", is.readLong());
jo.put("clanName", is.readString());
jo.put("clanBadge", is.readInt());
jo.put("clanRole", is.readInt());
jo.put("clanLevel", is.readInt());
}
byte a = is.readByte();
if(a == 1){
is.skipBytes(52);
}else if(a == 0 && isInClan == 2){
is.skipBytes(51);
}else if(a == 0 && isInClan == 0){
is.skipBytes(43);
}else{
is.skipBytes(44);
}
jo.put("league", is.readInt());
jo.put("clanCaslteLevel", (is.readInt() + 1));
jo.put("maxCcTroops", is.readInt());
is.readInt();
jo.put("townHall", (is.readInt() + 1));
jo.put("userName", is.readString());
is.readInt();
jo.put("level", is.readInt());
jo.put("exp", is.readInt());
jo.put("gems", is.readInt());
jo.put("freeGems", is.readInt());
jo.put("Attack Rating", is.readInt());
jo.put("Attack K Factor", is.readInt());
jo.put("Trophies", is.readInt());
jo.put("Attacks Won", is.readInt());
jo.put("Attacks Lost", is.readInt());
jo.put("Defenses Won", is.readInt());
jo.put("Defenses Lost", is.readInt());
is.readInt();
is.readInt();
is.readInt();
boolean isPlayerTagAvailable = is.readBoolean();
if (isPlayerTagAvailable) {
jo.put("nameTag", is.readLong());
}
jo.put("userNameChange", is.readBoolean());
jo.put("numOfNameChanges", is.readInt());
jo.put("boughtGems", is.readInt());
is.readInt();
jo.put("inWar", is.readInt());
Gson gson = new GsonBuilder().setPrettyPrinting().create();
ArrayList<DataSlot> rcl = DataSlot.readDataSlots(is);
String rcll = gson.toJson(rcl);
jo.put("resourcesCapList",rcll);
ArrayList<DataSlot> rl = DataSlot.readDataSlots(is);
String rll = gson.toJson(rl);
jo.put("resourcesList",rll);
}
底部的最后两位应该生成自己的数组,对吗?
这是输出(其中一部分)
{
"Trophies": 1262,
"clanLevel": 1,
"resourcesCapList": "[\n {\n \"value\": 2001000,\n \"globalID\": 3000001\n },\n {\n \"value\": 1251000,\n \"globalID\": 3000002\n },\n {\n \"value\": 0,\n \"globalID\": 3000003\n },\n {\n \"value\": 250000,\n \"globalID\": 3000004\n },\n {\n \"value\": 250000,\n \"globalID\": 3000005\n },\n {\n \"value\": 1000,\n \"globalID\": 3000006\n }\n]",
"resourcesList": "[\n {\n \"value\": 0,\n \"globalID\": 3000001\n },\n {\n \"value\": 0,\n \"globalID\": 3000002\n }\n]",
"Attack K Factor": -1653840941,
"Attacks Won": 0,
"freeGems": -2037996665,
"clanBadge": 1526737746,
"clanCaslteLevel": 2,
"currentHomeId": 1,
"clanRole": 2
}
为什么resourceCapList和resourceList这么乱?他们不应该以漂亮的方式打印吗?
还有什么办法可以保持元素的顺序相同吗?
最佳答案
已修复:)
感谢 blm 提供的帮助!
ArrayList<DataSlot> rcl = DataSlot.readDataSlots(is);
String rcll = gson.toJson(rcl);
JSONArray rcla = new JSONArray(rcll);
jo.put("resourcesCapList",rcla)
我刚刚将字符串转换为 JSONArray 并且它起作用了:)
关于java - JSON gson 解析为\n,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33009330/