1
我已經找遍了,發現了一些很好的答案,但我無法讓它工作。我發現這個線程(Parsing single json entry to multiple objects with Gson),但我不明白我的問題在哪裏。 我想將文件讀入新的對象(如果有可能只有一個更好,但我不知道如何)。 首先整型線程然後工具的陣列(其中每一個工具是一個對象)使用GSON多個陣列進行JAVA解析
這是我的TXT文件:
{
"threads": 4,
"tools": [
{
"tool": "gs-driver",
"qty": 35
},
{
"tool": "np-hammer",
"qty": 17
},
{
"tool": "rs-pliers",
"qty": 23
}
]
}
這是我的deseralization類,和兩個我的對象類
的import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.List;
public class Deserializer implements JsonDeserializer<ParseJson> {
public ParseJson deserialize(JsonElement json, Type type,
JsonDeserializationContext context) throws JsonParseException {
JsonObject obj = json.getAsJsonObject();
ParseJson test = new ParseJson();
test.setThreads(obj.get("threads").getAsInt());
Gson toolsGson = new Gson();
Type toolsType = new TypeToken<List<ParseTool>>(){}.getType();
List<ParseTool> toolsList = toolsGson.fromJson(obj.get("tools"), toolsType);
test.setTools(toolsList);
return test;
}
}
import java.util.List;
public class ParseJson {
private int threads;
private List<ParseTool> tools;
public void setThreads(int _threads) {
this.threads = _threads;
}
public int getThreads() {
return threads;
}
public void setTools(List<ParseTool> tools) {
this.tools = tools;
}
public List<ParseTool> getTools() {
return tools;
}
}
public class ParseTool {
private int qty;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
}
我可以得到「線程」,但由於某種原因它不解析數組。
感謝,
十分感謝,錯過了。 – Ace66
@ Ace66如果此問題解決了您的問題,您是否願意提供可接受的標記(至答案的左上角)? :-) –