[英]Google Gson not deserializing simple object with ArrayList properly
I am trying out Gson, but I cannot get past this issue. 我正在尝试Gson,但无法解决这个问题。
What ends up happening is the Network class gets created (my JSON root) and three layers are added. 最终发生的事情是创建了Network类(我的JSON根),并添加了三层。 These 3 Layers do not have the right "input" or "output" values set (both are 0).
这3个层没有设置正确的“输入”或“输出”值(均为0)。
I am expecting three layers with input and output values above 0. 我期望输入和输出值大于0的三层。
Below is my JSON and the code for the classes and Gson. 以下是我的JSON以及类和Gson的代码。
Can anyone tell me what is wrong? 谁能告诉我这是怎么回事? Is it my JSON structure or Java structure?
是我的JSON结构还是Java结构?
Gson code: 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);
}
I have a very very simple JSON like so (EDITED per discussion below) : 我有一个非常非常简单的JSON, 如下所示(根据下面的讨论进行编辑) :
{
"layers" : [
{"layer":
{"input":300,
"output":8000}
},
{"layer2":
{"input":300,
"output":8000}
},
{"layer3":
{"input":300,
"output":8000}
}
]
}
Here is the Layer class: 这是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;
}
}
And here is the class that contains an array list of layers: import java.util.ArrayList; 这是包含图层数组列表的类:import java.util.ArrayList;
public class Network {
ArrayList<Layer> layers;
public Network() {
layers = new ArrayList<Layer>();
}
public void addLayer(Layer l) {
layers.add(l);
}
}
Your JSON (and the respective POJO) structure should probably look like this: 您的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;
}
If each layer also have a name (or a label), it should have the following structure: 如果每个图层还具有名称(或标签),则其应具有以下结构:
{
"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.