74

I need to serialize some objects to a JSON and send to a WebService. How can I do it using the org.json library? Or I'll have to use another one? Here is the class I need to serialize:

public class PontosUsuario {

    public int idUsuario;
    public String nomeUsuario;
    public String CPF;
    public String email;
    public String sigla;
    public String senha;
    public String instituicao;

    public ArrayList<Ponto> listaDePontos;


    public PontosUsuario()
    {
        //criando a lista
        listaDePontos = new ArrayList<Ponto>();
    }

}

I only put the variables and the constructor of the class but it also have the getters and setters. So if anyone can help please

AurA
  • 12,135
  • 7
  • 46
  • 63
Tiago Geanezini
  • 917
  • 1
  • 7
  • 16

7 Answers7

109

Easy way to do it without annotations is to use Gson library

Simple as that:

Gson gson = new Gson();
String json = gson.toJson(listaDePontos);
Tombart
  • 30,520
  • 16
  • 123
  • 136
Bitman
  • 1,996
  • 1
  • 15
  • 18
  • 1
    Great little libary and works with dot42 if you import jar, but it puts all these `_backingFields_` into the JSON. I tried DataMembers but it didnt help. So I reverted to `StringBuilder` and just did it the KISS way. – Piotr Kula Aug 07 '14 at 21:38
  • 1
    It is very good for small-size objects. Lots of problems happen when objects are complex, especially if child object reference parent objects – MFARID Apr 08 '15 at 04:37
  • @MFARID would you know of an alternative for Android? like JSON.Net is for .Net? – Val Okafor Apr 08 '15 at 15:28
  • Just knew Gson is maintained by Google, so it seems much reliable for me to adopt. Looking at their user manual, it does take some time to customize it if you need to do so, writing your own serializer and de-serializer classes. – Shawn Jan 28 '20 at 20:56
27

One can use the Jackson library as well.

Add Maven Dependency:

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId> 
  <artifactId>jackson-core</artifactId>
</dependency>

Simply do this:

ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString( serializableObject );
Anand Singh
  • 1,091
  • 13
  • 21
techjourneyman
  • 1,701
  • 3
  • 33
  • 53
9

The quickest and easiest way I've found to Json-ify POJOs is to use the Gson library. This blog post gives a quick overview of using the library.

ryanbateman
  • 169
  • 3
5

You make the http request

HttpResponse response = httpclient.execute(httpget);           
HttpEntity entity = response.getEntity();

inputStream = entity.getContent();

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();

You read the Buffer

String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
Log.d("Result", sb.toString());
result = sb.toString();

Create a JSONObject and pass the result string to the constructor:

JSONObject json = new JSONObject(result);

Parse the json results to your desired variables:

String usuario= json.getString("usuario");
int idperon = json.getInt("idperson");
String nombre = json.getString("nombre");

Do not forget to import:

import org.json.JSONObject;
Carlos Landeras
  • 11,025
  • 11
  • 56
  • 82
  • This solutiuon has really poor performance on android (well, we do not speak about some small JSON , in this case it does not matter - but small data amounts tend to grow) - you are allocating too much objects ( JSON PArser uses DOM model ) and memory. You shall go for pull parser mode without allocating buffers. Also GSON ir JAckson is your friend here – Konstantin Pribluda May 17 '13 at 12:05
  • I am using this code in some production apps and it is working like a charm, and you do not need to use third party libraries. – Carlos Landeras May 17 '13 at 12:10
  • No doubt this approach works. It works like charm for small amnount of JSON. I also used this approach - but my higscore lists are bigger now, and allocation of spare buffer, of DOM tree and then parsing of JSON entities became unusable. Now I do not allocate buffers and just use pull parser with homegrown databindung. – Konstantin Pribluda May 17 '13 at 12:13
  • Interesting @KonstantinPribluda, in my case I dont move too much Data. What method do you recommend then?. Could you give me some links? Thanks – Carlos Landeras May 17 '13 at 12:14
  • 1
    Memoery and objewct allocation is expensive on android (much more thanon server). Recomendations are simple - try to avoid memory and object allocation. Use pull parser like GSON, and use databinding on top of it ( either one from GSON, or my small framework: https://github.com/ko5tik/jsonserializer - see unit tests forexample usage ) – Konstantin Pribluda May 17 '13 at 12:39
3

GSON is easy to use and has relatively small memory footprint. If you loke to have even smaller footprint, you can grab:

https://github.com/ko5tik/jsonserializer

Which is tiny wrapper around stripped down GSON libraries for just POJOs

Konstantin Pribluda
  • 12,329
  • 1
  • 30
  • 35
2

After JAVAEE8 published , now you can use the new JAVAEE API JSON-B (JSR367)

Maven dependency :

<dependency>
    <groupId>javax.json.bind</groupId>
    <artifactId>javax.json.bind-api</artifactId>
    <version>1.0</version>
</dependency>

<dependency>
    <groupId>org.eclipse</groupId>
    <artifactId>yasson</artifactId>
    <version>1.0</version>
</dependency>

<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.json</artifactId>
    <version>1.1</version>
</dependency>

Here is some code snapshot :

Jsonb jsonb = JsonbBuilder.create();
// Two important API : toJson fromJson
String result = jsonb.toJson(listaDePontos);

JSON-P is also updated to 1.1 and more easy to use. JSON-P 1.1 (JSR374)

Maven dependency :

<dependency>
    <groupId>javax.json</groupId>
    <artifactId>javax.json-api</artifactId>
    <version>1.1</version>
</dependency>

<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.json</artifactId>
    <version>1.1</version>
</dependency>

Here is the runnable code snapshot :

String data = "{\"name\":\"Json\","
                + "\"age\": 29,"
                + " \"phoneNumber\": [10000,12000],"
                + "\"address\": \"test\"}";
        JsonObject original = Json.createReader(new StringReader(data)).readObject();
        /**getValue*/
        JsonPointer pAge = Json.createPointer("/age");
        JsonValue v = pAge.getValue(original);
        System.out.println("age is " + v.toString());
        JsonPointer pPhone = Json.createPointer("/phoneNumber/1");
        System.out.println("phoneNumber 2 is " + pPhone.getValue(original).toString());
wodong
  • 297
  • 2
  • 10
1

The "reference" Java implementation by Sean Leary is here on github. Make sure to have the latest version - different libraries pull in versions buggy old versions from 2009.

Java EE 7 has a JSON API in javax.json, see the Javadoc. From what I can tell, it doesn't have a simple method to marshall any object to JSON, you need to construct a JsonObject or a JsonArray.

import javax.json.*;

JsonObject value = Json.createObjectBuilder()
 .add("firstName", "John")
 .add("lastName", "Smith")
 .add("age", 25)
 .add("address", Json.createObjectBuilder()
     .add("streetAddress", "21 2nd Street")
     .add("city", "New York")
     .add("state", "NY")
     .add("postalCode", "10021"))
 .add("phoneNumber", Json.createArrayBuilder()
     .add(Json.createObjectBuilder()
         .add("type", "home")
         .add("number", "212 555-1234"))
     .add(Json.createObjectBuilder()
         .add("type", "fax")
         .add("number", "646 555-4567")))
 .build();

JsonWriter jsonWriter = Json.createWriter(...);
jsonWriter.writeObject(value);
jsonWriter.close();

But I assume the other libraries like GSON will have adapters to create objects implementing those interfaces.

Ondra Žižka
  • 43,948
  • 41
  • 217
  • 277