Ace66
Ace66

Reputation: 153

JAVA parsing with GSON multiple arrays

I've looked all over and found some good answers to my question but i can't get it to work. I found this thread (Parsing single json entry to multiple objects with Gson) but i don't understand where my problem is. I want to read the file into new Objects (if it's possible with just one then even better but i couldn't find out how). First the int threads and then the array of tools(where each tool is an Object)

This is my TXT file :

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

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

this is my deseralization class, and two of my object classes

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

I can get the "threads" but it doesn't parse the array for some reason.

Thanks,

Upvotes: 1

Views: 408

Answers (1)

Olivier Gr&#233;goire
Olivier Gr&#233;goire

Reputation: 35467

ParseTool contains a propery named name, but the JSON indicates that it's named tool.

You should therefore rename the property name to 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;
    }
}

Upvotes: 1

Related Questions