Xeyler Xeyler - 1 year ago 155
Java Question

Parse Json with Children Parameters

I'm a little clueless on this subject, but I'm trying to parse some Json into variables using GSON.

Here's an example of part of the Json I'm trying to parse. The goal is to get an array of objects containing the .ogg path(i.e. "minecraft/sounds/mob/stray/death2.ogg") as well as its corresponding hash variable.

"objects": {
"minecraft/sounds/mob/stray/death2.ogg": {
"hash": "d48940aeab2d4068bd157e6810406c882503a813",
"size": 18817
"minecraft/sounds/mob/husk/step4.ogg": {
"hash": "70a1c99c314a134027988106a3b61b15389d5f2f",
"size": 9398

Any help or suggestions on how to get that sort of result with GSON would be appreciated.

Answer Source

Xeyeler , the following is a solution that will work. A better way is to look at how GSON can convert this to an object directly. I have not tried it though

import java.util.Map;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class MainProgram {

    public static void main(String[] args) {
        String mineCraft = "{  \"objects\": {    \"minecraft/sounds/mob/stray/death2.ogg\": {      \"hash\": \"d48940aeab2d4068bd157e6810406c882503a813\",      \"size\": 18817    },    \"minecraft/sounds/mob/husk/step4.ogg\": {      \"hash\": \"70a1c99c314a134027988106a3b61b15389d5f2f\",      \"size\": 9398    }}}";
        JsonParser parser = new JsonParser();
        JsonObject objects = parser.parse(mineCraft).getAsJsonObject().get("objects").getAsJsonObject();

        for (Map.Entry<String, JsonElement> entry : objects.entrySet()) {
            String oggFileName = entry.getKey();
            JsonElement attributes = entry.getValue();
                    "Key is " + oggFileName + " and the hash value is " + attributes.getAsJsonObject().get("hash"));

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download