Ways to create JSON objects in Java

The following is the JSON body that I want to use in iOS (Swift) and Android (Java) applications.

{
    "type" : "select",
    "args" : {
        "table"  : "todo",
        "columns": ["id", "title","completed"],
        "where"  : {"user_id": 1}
    }
}

In Swift, it is quite simple and easy to convert the above into a dictionary:

let params: [String: Any] = [
  "type" : "select",
  "args" : [
    "table"     : "todo",
    "columns"   : ["id","title","completed"],
    "where"     : ["user_id" : 1]
  ]
]

In Java, I use GSON to accomplish the above, but I feel that my solution is ugly and too long

public class SelectQuery {

    @SerializedName("type")
    String type = "select";

    @SerializedName("args")
    Args args;

    public SelectTodoQuery(=) {
        args = new Args();
        args.where = new Where();
        args.where.userId = 1;
    }

    class Args {

        @SerializedName("table")
        String table = "todo";

        @SerializedName("columns")
        String[] columns = {
                "id","title","completed"
        };

        @SerializedName("where")
        Where where;

    }

    class Where {
        @SerializedName("user_id")
        Integer userId;
    }

}

Is there a better way to do this in Java, and also how can I introduce this JSON in Java initially, without using GSON?

UPDATE

I do not ask for a list of libraries that help me complete the above, I already know about them and obviously use it. I also do not need to know about their performance. I ask for a better implementation (if it exists), and if Java does not provide such a function, this may be the accepted answer. In addition, an example for the same as in Java.

+4
2

, , - json.

GSON , POJO ( java-) json .

LoganSquare - , , .

Github LoganSquare .

enter image description here

, Moshi Jackson, , LoganSquare .

Native, Java , - Third partylibs, , , - , , usecases.

+1

Gson - , , :

final GsonBuilder builder = new GsonBuilder();
final Gson gson = builder.enableComplexMapKeySerialization().create();
final Type type = new TypeToken<Map<String, Args>>(){}.getType();

// deserialize from a string (read your file to string maybe)
HashMap<String, Args> aMap = gson.fromJson(aJSONString, type);
0

Source: https://habr.com/ru/post/1667735/


All Articles