Search code examples
javajsongson

How to retrieve data from a JSON file using Gson library


I have a JSON file that I parsed using Gson and I want to retrieve a variable named "ModelUrl" inside of it. As it seems, the data is a subdata of another node or data whatever you call and because of it I can not get the values that I want from the variable. I tried using such a function like: System.out.println(jsonObject.get("ModelUrl")), but it only returns null. How can I iterate in all the variables inside and get the variable that I specifically want?

Data is kinda big to put here, but I am gonna put a example to show what I mean by saying "subdata".

https://drive.google.com/file/d/11Ukmu9QjFPN3GCnr0Rp3QzHmoxm8XmUs/view?usp=sharing

Here is the data if you want to look.

"CatalogList":{"Items":[{"HasCampaignBanners":false,"ModelId":6280454,"ModelUrl":"/tr-TR/TR/urun/LC-WAIKIKI/kadin/Tunik/6280454/2747034","DefaultOptionImageUrl":"https://img-lcwaikiki.mncdn.com/mnresize/600/-/pim/productimages/20222/6280454/v1/l_20222-w2ic27z8-r3e-78-61-93-174_a.jpg","OptionImageUrlList":["https://img-lcwaikiki.mncdn.com/mnresize/600/-/pim/productimages/20222/6280454/v1/l_20222-w2ic27z8-r3e-78-61-93-174_a.jpg","https://img-lcwaikiki.mncdn.com/mnresize/600/-/pim/productimages/20222/6280454/v1/l_20222-w2ic27z8-r3e-78-61-93-174_a1.jpg","https://img-lcwaikiki.mncdn.com/mnresize/600/-/pim/productimages/20222/6280454/v1/l_20222-w2ic27z8-r3e-78-61-93-174_a2.jpg"]}

//Something like this. 

And here is the basic script that I wrote for retrieving data.

JsonElement jsonElement = JsonParser.parseString(data);
JsonObject jsonObject = jsonElement.getAsJsonObject();
System.out.println(jsonObject.get("ModelUrl"));



Solution

  • Not sure about your JSON data, but based on the problem which you stated giving a general solution:

    //Assuming JSON data is stored in a String with the name jsonData
    //Parse JSON
    
    JsonObject jsonObject = new Gson().fromJson(jsonData, JsonObject.class);
    
    //Assuming it's inside MenuItemList
    
    JsonArray menuItemList = jsonObject.getAsJsonObject("Menu").getAsJsonArray("MenuItemList");
    
    // Iterate array
    
    for (JsonElement element : menuItemList) {
        JsonObject menuItem = element.getAsJsonObject();
        String modelUrl = menuItem.get("ModelUrl").getAsString();
        System.out.println(modelUrl);
    }
    

    It's not a solution to your problem, but it may help you to understand.