Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help parsing json file using gson

Tags:

android

gson

Edit: I've changed the style of the json file to make it simpler as I couldn't work with the older version. I need to be able to create an array of targets in java where each element in the array has its name as the value of Target_Name. I also need to be able to merge together repeating target names that have different object names. So basically I want a target array and within each element I want to have an array of objects holding Type, Pin_number and capabilities.

I know I may have to create a Target list class and within that variables for target name and everything else. I have tried something like that before but I had trouble figuring out how it 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": "----"
    }
]

}

like image 731
zms6445 Avatar asked Nov 04 '22 18:11

zms6445


1 Answers

It's pretty straight forward, following is some code how to load and read nodes. It will help you to find out how to query your data.

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

// your json parsing is going to look like following

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, ....));
}

// Examples of how to read values and query objects

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();
like image 89
Maxim Avatar answered Nov 14 '22 23:11

Maxim