简体   繁体   中英

Google Gson not deserializing simple object with ArrayList properly

I am trying out Gson, but I cannot get past this issue.

What ends up happening is the Network class gets created (my JSON root) and three layers are added. These 3 Layers do not have the right "input" or "output" values set (both are 0).

I am expecting three layers with input and output values above 0.

Below is my JSON and the code for the classes and Gson.

Can anyone tell me what is wrong? Is it my JSON structure or Java structure?

Gson code:

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) :

{
  "layers" : [

    {"layer":
      {"input":300,
      "output":8000}
    },
    {"layer2":
      {"input":300,
      "output":8000}
    },
    {"layer3":
      {"input":300,
      "output":8000}
    }
  ]
}

Here is the Layer class:

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;

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:

    {
      "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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM