How to parse list of JSON objects surrounded by [] using Retrofit and GSON?

Recently I just finish one project related to retrofit2. Based on my source, I copy all your stuff into my project to give a try, making some minor change, it works well on my side. In your build.gradle, add those: compile ‘com.squareup.retrofit2:retrofit:2.0.1’ compile ‘com.google.code.gson:gson:2.6.2’ compile ‘com.squareup.okhttp3:okhttp:3.1.2’ compile ‘com.squareup.retrofit2:converter-gson:2.0.1’ compile ‘com.squareup.okhttp3:logging-interceptor:3.2.0′ Model: (UPDATE: Follow tommus’s case, … Read more

How to prevent Gson from converting a long number (a json string ) to scientific notation format?

If serializing to a String is an option for you, you can configure GSON to do so with: GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.setLongSerializationPolicy( LongSerializationPolicy.STRING ); Gson gson = gsonBuilder.create(); This will produce something like: {numbers : [ “268627104”, “485677888”, “506884800” ] }

Gson add field during serialization

Use Gson.toJsonTree to get a JsonElement, with which you can interact dynamically. A a = getYourAInstanceHere(); Gson gson = new Gson(); JsonElement jsonElement = gson.toJsonTree(a); jsonElement.getAsJsonObject().addProperty(“url_to_user”, url); return gson.toJson(jsonElement);

dump object to String with Jackson

To serialize with Jackson: public String serialize(Object obj, boolean pretty) { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); if (pretty) { return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj); } return mapper.writeValueAsString(obj); }

How to convert ArrayList of custom class to JsonArray in Java?

Below code should work for your case. List<Customer> customerList = CustomerDB.selectAll(); Gson gson = new Gson(); JsonElement element = gson.toJsonTree(customerList, new TypeToken<List<Customer>>() {}.getType()); if (! element.isJsonArray() ) { // fail appropriately throw new SomeException(); } JsonArray jsonArray = element.getAsJsonArray(); Heck, use List interface to collect values before converting it JSON Tree.

tech