How to serialize Object to JSON?

JavaAndroidJson

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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

Simple as that:

Gson gson = new Gson();
String json = gson.toJson(listaDePontos);

Solution 2 - Java

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 );

Solution 3 - Java

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.

Solution 4 - Java

>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;

Solution 5 - Java

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

Solution 6 - Java

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.

Solution 7 - Java

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());

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTiago GeaneziniView Question on Stackoverflow
Solution 1 - JavaBitmanView Answer on Stackoverflow
Solution 2 - JavatechjourneymanView Answer on Stackoverflow
Solution 3 - JavaryanbatemanView Answer on Stackoverflow
Solution 4 - JavaCarlos LanderasView Answer on Stackoverflow
Solution 5 - JavaKonstantin PribludaView Answer on Stackoverflow
Solution 6 - JavaOndra ŽižkaView Answer on Stackoverflow
Solution 7 - JavawodongView Answer on Stackoverflow