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 t
Easy way to do it without annotations is to use Gson library
Simple as that:
Gson gson = new Gson();
String json = gson.toJson(listaDePontos);
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.
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;
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.
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 );
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());