Need help parsing json file using gson

Edit: I changed the style of the json file to make it simpler, since I could not work with the old version. I need to create an array of targets in java, where each element in the array has its own name as the value of Target_Name. I should also be able to combine duplicate target names that have different object names. So basically I want a target array, and inside each element I want to have an array of objects containing Type, Pin_number and features.

I know, I might have to create a goal list class inside these variables for the target name and everything else. I already tried something similar, but it was hard for me to understand how this would work.

    {
"Targets": [
    {
        "Target_Name": "----",
        "Object_Name": "----",
        "Type": "----",
        "Pin_Number": "----",
        "Capabilities": "----"
    },
    {
        "Target_Name": "----",
        "Object_Name": "----",
        "Type": "----",
        "Pin_Number": "----",
        "Capabilities": "----"
    },
    {
        "Target_Name": "----",
        "Object_Name": "----",
        "Type": "----",
        "Pin_Number": "----",
        "Capabilities": "----"
    },
    {
        "Target_Name": "----",
        "Object_Name": "----",
        "Type": "----",
        "Pin_Number": "----",
        "Capabilities": "----"
    }
]

}

+5
source share
1

, . , .

Reader reader = null;
InputStream stream = context.getResources()
    .openRawResource(R.raw.json_file);
reader = new BufferedReader(new InputStreamReader(stream), 8092);

// parse json
JsonParser parser = new JsonParser();
JsonObject jsonObj = (JsonObject)parser.parse(reader);

// json

JsonArray targets= jsonObj.getAsJsonArray("Targets");

List<Target> targetList = new ArrayList<Target>(); 
for (JsonElement target: targets) {

    JsonObject targetObject = target.getAsJsonObject();
    String targetName= targetObject.get("Target_Name").getAsString();
    ....//get the rest

    // create target object
    targetList.add(new Target(targetName, ....));
}

//

for (Entry<String, JsonElement> entry : rootElem.entrySet())
{
    int key = Integer.parseInt(entry.getKey());
    JsonObject jsonObject = entry.getValue().getAsJsonObject();
}


// get integer element
int key = Integer.parseInt(entry.getKey());

// get child object
JsonObject jsonObject = entry.getValue().getAsJsonObject();

// get string element           
String title = jsonObject.get("Object_Name").getAsString();
+2

All Articles