[英]Google Gson not deserializing simple object with ArrayList properly
我正在嘗試Gson,但無法解決這個問題。
最終發生的事情是創建了Network類(我的JSON根),並添加了三層。 這3個層沒有設置正確的“輸入”或“輸出”值(均為0)。
我期望輸入和輸出值大於0的三層。
以下是我的JSON以及類和Gson的代碼。
誰能告訴我這是怎么回事? 是我的JSON結構還是Java結構?
Gson代碼:
try(Reader reader = new InputStreamReader(ModelLoader.class.getResourceAsStream("/test.json"), "UTF-8")){
Gson gson = new GsonBuilder().create();
Network n = gson.fromJson(reader, Network.class);
System.out.println(n);
}
我有一個非常非常簡單的JSON, 如下所示(根據下面的討論進行編輯) :
{
"layers" : [
{"layer":
{"input":300,
"output":8000}
},
{"layer2":
{"input":300,
"output":8000}
},
{"layer3":
{"input":300,
"output":8000}
}
]
}
這是Layer類:
public class Layer {
int input;
int output;
float[][] weights;
float[] inputs;
float[] outputs;
public Layer(int input, int output) {
...constructor code initializes vars...
}
public void setInput(int input) {
this.input = input;
}
public void setOutput(int output) {
this.output = output;
}
public void setInputs(float[] inputs) {
this.inputs = inputs;
}
public void setWeight(float[][] weights) {
this.weights = weights;
}
}
這是包含圖層數組列表的類:import java.util.ArrayList;
public class Network {
ArrayList<Layer> layers;
public Network() {
layers = new ArrayList<Layer>();
}
public void addLayer(Layer l) {
layers.add(l);
}
}
您的JSON(以及相應的POJO)結構應該看起來像這樣:
{
"layers" : [
{"input":300,output":8000},
{"input":300,"output":8000},
{"input":300,"output":8000}
]
}
public class Layer {
int input;
int output;
}
public class Network {
ArrayList<Layer> layers;
}
如果每個圖層還具有名稱(或標簽),則其應具有以下結構:
{
"layers" : [
{"label":"layer", "input":300,output":8000},
{"label":"layer1", "input":300,"output":8000},
{"label":"layer2", "input":300,"output":8000}
]
}
public class Layer {
int input;
int output;
String label;
}
public class Network {
ArrayList<Layer> layers;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.