【问题标题】:Google Gson not deserializing simple object with ArrayList properly谷歌 Gson 没有正确反序列化带有 ArrayList 的简单对象
【发布时间】:2016-11-18 00:35:11
【问题描述】:

我正在尝试 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}
    }
  ]
}

这是图层类:

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

这是包含层数组列表的类: 导入 java.util.ArrayList;

public class Network {

    ArrayList<Layer> layers;

    public Network() {
        layers = new ArrayList<Layer>();
    }

    public void addLayer(Layer l) {
        layers.add(l);
    }
}

【问题讨论】:

  • layer、layer2 和 layer3 应该映射到什么位置?
  • @SotiriosDelimano 是一个图层类。
  • 为什么?在您的课程组中,您在哪里有名为 layer、layer2 或 layer3 的东西?
  • @SotiriosDelimanolis 我有一个 Layer 类,我的 Network 有一个 Layer 类型的 ArrayList。
  • 让我换个说法。您期望名为 input 的 JSON 对将映射到名为 input 的 Layer 对象的字段。好吧,让我们上一个层次。名为 layer1 的 JSON 对将映射到哪个字段?

标签: java json parsing gson


【解决方案1】:

您的 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;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-25
    • 2021-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-16
    相关资源
    最近更新 更多