【问题标题】:JAVA parsing with GSON multiple arrays使用 GSON 多个数组进行 JAVA 解析
【发布时间】:2016-12-24 11:17:53
【问题描述】:

我已经查看了所有内容,并找到了一些很好的问题答案,但我无法让它发挥作用。我找到了这个帖子(Parsing single json entry to multiple objects with Gson),但我不明白我的问题出在哪里。 我想将文件读入新的对象(如果可以的话,那就更好了,但我不知道怎么做)。 首先是 int 线程,然后是工具数组(其中每个工具都是一个对象)

这是我的 TXT 文件:

    {
"threads": 4,
"tools": [

{
"tool": "gs-driver",
"qty": 35
},
{
"tool": "np-hammer",
"qty": 17
},
{
"tool": "rs-pliers",
"qty": 23
}
]
}

这是我的反序列化类,以及我的两个对象类

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

我可以获得“线程”,但由于某种原因它不解析数组。

谢谢,

【问题讨论】:

    标签: java arrays json gson


    【解决方案1】:

    ParseTool 包含一个名为 name 的属性,但 JSON 表明它名为 tool

    因此,您应该将属性 name 重命名为 tool

    public class ParseTool {
    
        private int qty;
        private String tool;
    
        public String getTool() {
            return tool;
        }
    
        public void setTool(String tool) {
            this.tool = tool;
        }
    
        public int getQty() {
            return qty;
        }
    
        public void setQty(int qty) {
            this.qty = qty;
        }
    }
    

    【讨论】:

    • 太好了!谢谢,错过了。
    • @Ace66 如果这解决了您的问题,您是否愿意提供已接受的标记(答案的左上角)? :-)
    猜你喜欢
    • 1970-01-01
    • 2013-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多