Convert json to java class


How do I convert such a json to a Java class using GSON ?

{ "type": "success", "value": { "id": 61, "joke": "Chuck Norris once ate a whole cake before his friends could tell him there was a stripper in it.", "categories": [] } }

What will this class look like ?

Author: Anton Shchyrov, 2016-10-31

1 answers

In general, to do this, you need to create a class where the fields will be unloaded. The fields must be public and the class must contain an empty constructor.

public class MyClass {

    public String joke;
    public int id;
    public String[] categories; 

    // Конструктор
    public MyClass(){

    }
}

Next, it is simply unloaded into it from json

String jsonText = "{ \"id\": 61, \"joke\": \"Chuck Norris once ate a whole cake before his friends could tell him there was a stripper in it.\", \"categories\": [] }";

GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
MyClass myClass = gson.fromJson(jsonText, MyClass.class);
System.out.println("GSON", "id: " + myClass.id + "\njoke: " + myClass.joke);

I don't remember if you can use GSON to take the object value from the string that you have (it seems that you can judging by the information), but you can definitely get it from another library org.json.java-json.jar

Will it look like something like this:

import org.json.*;

public class Test {

    public static void main (String[] args) throws java.lang.Exception  {
        String json = "{ \"type\": \"success\", \"value\": { \"id\": 61, \"joke\": \"Chuck Norris once ate a whole cake before his friends could tell him there was a stripper in it.\", \"categories\": [] } }";
        JSONObject obj = new JSONObject(json);
        JSONObject myClassJSONObject = obj.getJSONObject("value");
    }
}
 5
Author: Алексей Шиманский, 2017-04-13 12:53:29