-2

I want to Deserialize the following JSON string to a POJO but I can't get a proper way of doing this with JSON-Java library (org.json).

Here is a JSON string that I want to parse:

{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters":
    {
        "batter":
            [
                { "id": "1001", "type": "Regular" },
                { "id": "1002", "type": "Chocolate" },
            ]
    },
"topping":
    [
        { "id": "5001", "type": "None" },
        { "id": "5002", "type": "Glazed" },
        { "id": "5005", "type": "Sugar" },
    ]
}

And this is a POJO that I want to Deserialize the JSON into:

import java.util.List;

public class  DeserializeJsonToPojo {
private String id;
private String type;
private String name;
private double ppu;
private Batters batters;
List<Toppings> toppings;

// getters and setters

public static class Batters {
    List<Bats> bats;

    // getters and setters

    public static class Bats {
        private String id;
        private String type;

        // getters and setters
    }
}

public static class Toppings {
    private String id;
    private String type;

    // getters and setters
    }
}

1 Answers1

-1

You can use com.google.code.gson.

If you're using Maven, you can add the following dependency:

<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>${version}</version>
</dependency>

After that you can just write the following code:

Gson gson = new Gson();
DeserializeJsonToPojo max = gson.fromJson(jsonAsString, DeserializeJsonToPojo.class);
Arpit Jindal
  • 504
  • 4
  • 7