Convert object to JSON in Android - java

Is there a simple method to convert any object to JSON in Android?

Most people are using gson : check this
Gson gson = new Gson();
String json = gson.toJson(myObj);

public class Producto {
int idProducto;
String nombre;
Double precio;
public Producto(int idProducto, String nombre, Double precio) {
this.idProducto = idProducto;
this.nombre = nombre;
this.precio = precio;
}
public int getIdProducto() {
return idProducto;
}
public void setIdProducto(int idProducto) {
this.idProducto = idProducto;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public Double getPrecio() {
return precio;
}
public void setPrecio(Double precio) {
this.precio = precio;
}
public String toJSON(){
JSONObject jsonObject= new JSONObject();
try {
jsonObject.put("id", getIdProducto());
jsonObject.put("nombre", getNombre());
jsonObject.put("precio", getPrecio());
return jsonObject.toString();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}

Might be better choice:
#Override
public String toString() {
return new GsonBuilder().create().toJson(this, Producto.class);
}

download the library Gradle:
implementation 'com.google.code.gson:gson:2.9.0'
To use the library in a method.
Gson gson = new Gson();
//transform a java object to json
System.out.println("json =" + gson.toJson(Object.class).toString());
//Transform a json to java object
String json = string_json;
List<Object> lstObject = gson.fromJson(json_ string, Object.class);

Spring for Android do this using RestTemplate easily:
final String url = "http://192.168.1.50:9000/greeting";
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
Greeting greeting = restTemplate.getForObject(url, Greeting.class);

As of Android 3.0 (API Level 11) Android has a more recent and improved JSON Parser.
http://developer.android.com/reference/android/util/JsonReader.html
Reads a JSON (RFC 4627) encoded value as a stream of tokens. This
stream includes both literal values (strings, numbers, booleans, and
nulls) as well as the begin and end delimiters of objects and arrays.
The tokens are traversed in depth-first order, the same order that
they appear in the JSON document. Within JSON objects, name/value
pairs are represented by a single token.

The Kotlin way
val json = Gson().toJson(myObj)

Anyway, you know this
Gson gson = new Gson();
String json = gson.toJson(yourModelClassReference);
You might have forget to add #Expose

Related

Extracting the value of an element from a JSON

I'm trying to make a test where I get some documents based on the id of the batch they belong to. More specifically, I want to check that a specific batchPublicId is in the response body. I am using okhttp for the test.
This a shorter version of the json:
{
"_embedded": {
"invoices": [
{
"type": "INVOICE",
"publicId": "27bc8426-17cf-4fe5-9278-64108ae05e4b",
"deliveryStatus": null,
"processingStatus": "INITIATED",
"batchPublicId": "0000000000000000000000001"
}
]
}
}
I'm new to json and this is how far I got with the problem:
String invoicesJsonData = response.body().string();
JSONObject invoicesJsonObject = new JSONObject(invoicesJsonData);
Assert.assertTrue(invoicesJsonObject.getJSONObject("_embedded") !=null && invoicesJsonObject.getJSONObject("_embedded").has("invoices"));
I would like to verify that batchPublicId has the value mentioned in the json. Is there a way to do this? Thank you.
String invoicesJsonData = response.body().string();
JSONObject invoicesJsonObject = new JSONObject(invoicesJsonData);
JSONObject invoicesJsonObject1 = invoicesJsonObject.getJSONObject("_embedded");
JSONArray f2=invoicesJsonObject1.getJSONArray("invoices");
for(int i=0;i<f2.length();i++){
JSONObject obj=f2.getJSONObject(i);
if(obj.get("batchPublicId")!=null){
System.out.println(obj.get("batchPublicId"));
}
You can do something like this,Which worked out for me sometimes back.
String invoicesJsonData = response.body().string();
JSONObject invoicesJsonObject = new JSONObject(invoicesJsonData);
JSONObject invoicesJsonObject = json.getJSONObject("invoicesJsonObject");
String batchPublicId = invoicesJsonObject.getString("batchPublicId");
System.out.println( "batchPublicId: " + batchPublicId );
if(batchPublicId !=null){
// do something
}
Not sure about the syntax.Giving you a hint.
you can check any keys is there in json object or not like below :
if(jsonObject1.has("batchPublicId")){
String batchPublicId = jsonObject1.optString("batchPublicId");
Log.i(getClass().getSimpleName(), "batchPublicId=" + batchPublicId);}
has method is used to find any key is there in jsonobject or not.
In my opinion, a better approach for this would be to create a POJO from this JSON string, and extract the information you need using simply the getters
For example:
Wrapper class:
#JsonIgnoreProperties(ignoreUnknown = true)
#JsonRootName(value = "_embedded")
public class Embeded {
#JsonProperty("invoices")
private List<Invoice> invoices;
public Embeded() {}
public List<Invoice> getInvoices() {
return invoices;
}
public void setInvoices(List<Invoice> invoices) {
this.invoices = invoices;
}
}
Invoice class:
#JsonIgnoreProperties(ignoreUnknown = true)
public class Invoice {
#JsonProperty("type")
private String type;
#JsonProperty("publicId")
private String publicId;
#JsonProperty("deliveryStatus")
private String deliveryStatus;
#JsonProperty("processingStatus")
private String processingStatus;
#JsonProperty("batchPublicId")
private String batchPublicId;
public Invoice() {}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getPublicId() {
return publicId;
}
public void setPublicId(String publicId) {
this.publicId = publicId;
}
public String getDeliveryStatus() {
return deliveryStatus;
}
public void setDeliveryStatus(String deliveryStatus) {
this.deliveryStatus = deliveryStatus;
}
public String getProcessingStatus() {
return processingStatus;
}
public void setProcessingStatus(String processingStatus) {
this.processingStatus = processingStatus;
}
public String getBatchPublicId() {
return batchPublicId;
}
public void setBatchPublicId(String batchPublicId) {
this.batchPublicId = batchPublicId;
}
}
Test:
public void json_test() throws JsonParseException, JsonMappingException, IOException {
String json = "{"
+ "\"_embedded\": {"
+ "\"invoices\": ["
+ "{"
+ "\"type\": \"INVOICE\","
+ "\"publicId\": \"27bc8426-17cf-4fe5-9278-64108ae05e4b\","
+ "\"deliveryStatus\": null,"
+ "\"processingStatus\": \"INITIATED\","
+ "\"batchPublicId\": \"0000000000000000000000001\""
+ "}"
+ "]"
+ "}"
+ "}";
ObjectMapper mapper = new ObjectMapper();
mapper.configure(Feature.UNWRAP_ROOT_VALUE, true);
List<Invoice> invoices = mapper.readValue(json, Embeded.class).getInvoices();
Assert.assertTrue(StringUtils.equals(invoices.get(0).getBatchPublicId(), "0000000000000000000000001"));
}
If I understand your right, you just need to call:
Assert.assertTrue(invoicesJsonObject.getString("batchPublicId").equals("0000000000000000000000001"));"
If you want to create a test for JSON Validation, you can use the JSONAssert.
JSONAsset give the method assertEquals, that compare two json structures, strict identic or not.
final String expected_result = YOUR_EXPECTED_RESULT;
JSONAssert.assertEquals(YOUR_EXPECTED_JSON_RESULT, RESULT_FROM_RESPONSE_BODY, false);
The last boolean parameter defines if you want an strict comparation or just compare if your expected result is in result from response.

Convert string to JSON and get value

I have this string:
{"markers":[{"tag":"1","dep":"2"}]}
How to convert it to JSON and get value tag and dep?
you need JSONObject to do this
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET,url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
String tag, dep;
JSONArray jArray = response.getJSONArray("markers");
JSONObject msg = jArray.getJSONObject(0);
tag = msg.getString("tag");
dep = msg.getString("dep");
}
}
try
{
JSONObject object = new JSONObject(json_str);
JSONArray array= object.getJSONArray("markers");
for(int i=0;i<array.length();i++)
{
JSONObject obj= array.getJSONObject(i);
String tag= obj.getString("tag");
int dep= obj.getInt("dep");
}
}catch(JSONException e){
}
Hope this helps.
it's good habbit to serialize the json to pojo object ..
here you can use Gson (a google library to serialize/deserialize json to pojo object)
Assuming you are using Android-Studio IDE for android development
Step 1 : add this gson dependency on build.gradle file of module scope
compile 'com.google.code.gson:gson:2.4'
Step 2: create model for json
{"markers":[{"tag":"1","dep":"2"}]}
Markers.java
public class Markers {
/**
* tag : 1
* dep : 2
*/
private List<MarkersEntity> markers;
public void setMarkers(List<MarkersEntity> markers) {
this.markers = markers;
}
public List<MarkersEntity> getMarkers() {
return markers;
}
public static class MarkersEntity {
private String tag;
private String dep;
public void setTag(String tag) {
this.tag = tag;
}
public void setDep(String dep) {
this.dep = dep;
}
public String getTag() {
return tag;
}
public String getDep() {
return dep;
}
}
}
Step 3: serialise json string to pojo object using gson
Gson gson = new Gson();
Markers markers = gson.fromJson(<jsonstring>.toString(), Markers.class);
Step 4: iterate the markers.getMarkersEntity() to get values of tag & dep
for(MarkersEntity data:markers.getMarkersEntity())
{
String tag = data.getTag();
String dep = data.getDep();
Log.d("JSON to Object", tag +"-"+dep);
}
You can use Ion Library for this and parse it as follows:
Ion.with(MainActivity.this).load("url").asJsonObject().setCallback(new FutureCallback<JsonObject>() {
#Override
public void onCompleted(Exception arg0, JsonObject arg1) {
// TODO Auto-generated method stub
if(arg0==null)
{
arg1.get("markers").getAsJsonArray();
JsonObject Jobj=arg1.getAsJsonObject();
String tag=Jobj.get("tag").getAsString();
String dep=Jobj.get("dep").getAsString();
}
}
});
Here, you may find your solution. Try it.
try {
//jsonString : {"markers": [{"tag":"1","dep":"2"}]}
JSONObject mainObject = new JSONObject(jsonString);
JSONArray uniArray = mainObject.getJSONArray("markers");
JSONObject subObject = uniArray.getJSONObject(0);
String tag = subObject.getString("tag");
String dep = subObject.getString("dep");
} catch (JSONException e) {
e.printStackTrace();
}

Android/java Parsing JSON with numbered data [duplicate]

This question already has answers here:
How to parse a dynamic JSON key in a Nested JSON result?
(5 answers)
Closed 7 years ago.
I have been looking for parsing JSON data in java/android. unfortunately, there is no JSON that same as mine. i have JSON data that include weird number, looks like :
{
"formules": [{"1":
{
"formule": "Linear Motion",
"url": "qp1"
},"2":
{
"formule": "Constant Acceleration Motion",
"url": "qp2"
},"3":
{
"formule": "Projectile Motion",
"url": "qp3"
}
}
]
}
Please help me how to parse this in Java/android. Thanks
try this
JSONObject jsonObject = new JSONObject(string);
JSONArray jsonArray = jsonObject.getJSONArray("formules");
JSONObject jsonObject1 = jsonArray.getJSONObject(0);
Now you can access object "1" as
JSONObject json = jsonObject1.getJSONObject("1");
or use iterator to iterate as below
Iterator keys = jsonObject1.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
JSONObject json = jsonObject1.getJSONObject(currentDynamicKey);
}
let me know if it works
For parsing Json in Android, I have found the Gson Library to be helpful
http://mvnrepository.com/artifact/com.google.code.gson/gson/2.3
What it would require is creating a pojo class that represents your object. Might look something like
public class ClassPojo
{
private Formules[] formules;
public Formules[] getFormules ()
{
return formules;
}
public void setFormules (Formules[] formules)
{
this.formules = formules;
}
#Override
public String toString()
{
return "ClassPojo [formules = "+formules+"]";
}
}
public class Formules
{
private Formule 3;
private Forumle 2;
private Formule 1;
}
public class Formule
{
private String formule;
private String url;
public String getFormule ()
{
return formule;
}
public void setFormule (String formule)
{
this.formule = formule;
}
public String getUrl ()
{
return url;
}
public void setUrl (String url)
{
this.url = url;
}
#Override
public String toString()
{
return "ClassPojo [formule = "+formule+", url = "+url+"]";
}
}
then to convert it to and from JSon,you could use
//Convert to JSON
ClassPojo pojo = new ClassPojo();
Gson gson = new Gson();
String json = gson.toJson(pojo);
//COnvert back to Java object
ClassPojo pojo = gson.fromJson(json,ClassPojo.class);

Faster way to parse a JSON String in android

I'm using this method to parse a JSON string, but it is too slow... is there a better way to do it?
Thanks
synchronized private void parseCategories(String response){
try{
JSONArray categoriesJSONArray = new JSONArray (response);
// looping through All Contacts
for(int i = 0; i < categoriesJSONArray.length(); i++){
JSONObject currentCategory = categoriesJSONArray.getJSONObject(i);
String label="";
String categoryId="";
// Storing each json item in variable
if(currentCategory.has("label"))
label = currentCategory.getString("label");
if(currentCategory.has("id"))
categoryId = currentCategory.getString("id");
if(
label!=null &&
categoryId!=null
)
{
Category toAdd = new Category(categoryId, label);
categories.add(toAdd);
}
}
//Alphabetic order
Collections.sort(
categories,
new Comparator<Feed>() {
public int compare(Feed lhs, Feed rhs) {
return lhs.getTitle().compareTo(rhs.getTitle());
}
}
);
Intent intent = new Intent("CategoriesLoaded");
LocalBroadcastManager.getInstance(mAppContext).sendBroadcast(intent);
}catch (JSONException e) {
e.printStackTrace();
}
}
Here's try following code to start with. You would need Gson library for it.
Gson gson=new Gson();
MyBean myBean=gson.fromJson(response);
Note: Here MyBean class contains the fields present in you json string for e.g. id, along with getter and setters. Rest of all is handled by Gson.
Here's a quick demo.
import com.google.gson.annotations.SerializedName;
public class Box {
#SerializedName("id")
private String categoryId;
// getter and setter
}
Say you JSON looks as following:
{"id":"A12"}
You can parse it as follows:
class Parse{
public void parseJson(String response){
Gson gson=new Gson();
Box box=gson.fromJson(response,Box.class);
System.out.println(box.getCategoryId());
}
}
Output :
A12
For more on Gson visit here
Use GSON library. You can convert your object to json string like the following example:
MyClass MyObject;
Gson gson = new Gson();
String strJson = gson.toJson(MyObject);

Returned List<Object> in JSON from C# and read in java application

here is the asmx method:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public String mtdImporteUsuario()
{
JavaScriptSerializer ser = new JavaScriptSerializer();
List<UsuarioBO> usuarios = new List<UsuarioBO>();
try
{
query = new Procedimientos().QSelectAllUsers();
ds = new ConexionBD().mtdEjecutaQuery_DS(query, "Usuarios");
foreach (DataRow dr in ds.Tables[0].Rows)
{
usuarios.Add(new UsuarioBO
{
O_COD = 1,
O_MENSAJE = "OK",
NId_usuario = Convert.ToInt32(dr["idusuario"]),
SCod_cuenta = dr["cuenta"].ToString(),
SCod_password = dr["password"].ToString(),
NNum_rut = Convert.ToInt32(dr["num_RutUsuario"]),
SDv_rut = dr["dv_RutUsuario"].ToString(),
SGls_nombre = dr["primer_nombre"].ToString(),
SGls_apellido_paterno = dr["apellido_paterno"].ToString(),
SGls_apellido_materno = dr["apellido_materno"].ToString(),
NId_perfil = Convert.ToInt32(dr["idperfil"])
});
}
}
catch (Exception ex)
{
throw ex;
}
return ser.Serialize(usuarios);
}
and the response is:
<?xml version="1.0" encoding="UTF-8"?>
<string xmlns="http://tempuri.org/">[{"O_COD":1,"O_MENSAJE":"OK","NId_usuario":4,"NId_perfil":1155,"NNum_rut":10584082,"SGls_nombre":"Juan","SCod_cuenta":"jancan","SCod_password":"12345","SFoto":"","SFotoOri":"","SGls_apellido_paterno":"Ancan","SGls_apellido_materno":"","SDv_rut":"9"},{"O_COD":1,"O_MENSAJE":"OK","NId_usuario":13,"NId_perfil":1155,"NNum_rut":10584080,"SGls_nombre":"Marco","SCod_cuenta":"msuazo","SCod_password":"msuazo","SFoto":"","SFotoOri":"","SGls_apellido_paterno":"Suazo","SGls_apellido_materno":"","SDv_rut":"2"},{"O_COD":1,"O_MENSAJE":"OK","NId_usuario":15,"NId_perfil":1122,"NNum_rut":10584082,"SGls_nombre":"Administrador","SCod_cuenta":"gallendes","SCod_password":"joi7jiuml","SFoto":"","SFotoOri":"","SGls_apellido_paterno":"","SGls_apellido_materno":"tratos","SDv_rut":"9"},{"O_COD":1,"O_MENSAJE":"OK","NId_usuario":16,"NId_perfil":1155,"NNum_rut":11072809,"SGls_nombre":"Juan","SCod_cuenta":"jchavez","SCod_password":"claudia","SFoto":"","SFotoOri":"","SGls_apellido_paterno":"Chavez","SGls_apellido_materno":"","SDv_rut":"3"},{"O_COD":1,"O_MENSAJE":"OK","NId_usuario":17,"NId_perfil":1155,"NNum_rut":11994419,"SGls_nombre":"German","SCod_cuenta":"gcabrera","SCod_password":"210372","SFoto":"","SFotoOri":"","SGls_apellido_paterno":"Cabrera","SGls_apellido_materno":"","SDv_rut":"8"},{"O_COD":1,"O_MENSAJE":"OK","NId_usuario":20,"NId_perfil":145,"NNum_rut":17203522,"SGls_nombre":"Jose Francisco","SCod_cuenta":"jfhurtado","SCod_password":"123","SFoto":"","SFotoOri":"","SGls_apellido_paterno":"Hurtado","SGls_apellido_materno":"Ruiz-Tagle","SDv_rut":"1"},{"O_COD":1,"O_MENSAJE":"OK","NId_usuario":21,"NId_perfil":1122,"NNum_rut":10584082,"SGls_nombre":"Roberto","SCod_cuenta":"tratos","SCod_password":"tratos","SFoto":"","SFotoOri":"","SGls_apellido_paterno":"Puga","SGls_apellido_materno":"Y.","SDv_rut":"9"},{"O_COD":1,"O_MENSAJE":"OK","NId_usuario":22,"NId_perfil":1155,"NNum_rut":18084387,"SGls_nombre":"Nazareno","SCod_cuenta":"nfigueroa","SCod_password":"supervisor","SFoto":"","SFotoOri":"","SGls_apellido_paterno":"Figueroa","SGls_apellido_materno":"","SDv_rut":"6"},{"O_COD":1,"O_MENSAJE":"OK","NId_usuario":23,"NId_perfil":1155,"NNum_rut":10584082,"SGls_nombre":"Jose Luis","SCod_cuenta":"jlramirez","SCod_password":"jose","SFoto":"","SFotoOri":"","SGls_apellido_paterno":"Ramirez","SGls_apellido_materno":"","SDv_rut":"9"},{"O_COD":1,"O_MENSAJE":"OK","NId_usuario":24,"NId_perfil":1155,"NNum_rut":10584082,"SGls_nombre":"Manuel","SCod_cuenta":"mcorrea","SCod_password":"manuel","SFoto":"","SFotoOri":"","SGls_apellido_paterno":"Correa","SGls_apellido_materno":"","SDv_rut":"9"},{"O_COD":1,"O_MENSAJE":"OK","NId_usuario":25,"NId_perfil":144,"NNum_rut":1,"SGls_nombre":"Administrador ","SCod_cuenta":"nubix","SCod_password":"admin","SFoto":"","SFotoOri":"","SGls_apellido_paterno":"","SGls_apellido_materno":"","SDv_rut":"9"},{"O_COD":1,"O_MENSAJE":"OK","NId_usuario":26,"NId_perfil":146,"NNum_rut":5777261,"SGls_nombre":"Franco","SCod_cuenta":"fnieri","SCod_password":"fnieri","SFoto":"","SFotoOri":"","SGls_apellido_paterno":"Nieri","SGls_apellido_materno":"","SDv_rut":"1"},{"O_COD":1,"O_MENSAJE":"OK","NId_usuario":27,"NId_perfil":1122,"NNum_rut":17248311,"SGls_nombre":"Camila Fernanda Valentina","SCod_cuenta":"cflores","SCod_password":"nene2302","SFoto":"","SFotoOri":"","SGls_apellido_paterno":"Flores","SGls_apellido_materno":"Haub","SDv_rut":"9"},{"O_COD":1,"O_MENSAJE":"OK","NId_usuario":28,"NId_perfil":1,"NNum_rut":1,"SGls_nombre":"nombreDermo","SCod_cuenta":"dermo","SCod_password":"dermo","SFoto":"","SFotoOri":"","SGls_apellido_paterno":"ApellidoPat","SGls_apellido_materno":"ApellidoMat","SDv_rut":"9"},{"O_COD":1,"O_MENSAJE":"OK","NId_usuario":29,"NId_perfil":1,"NNum_rut":1,"SGls_nombre":"dime","SCod_cuenta":"dimetu","SCod_password":"dimeyo","SFoto":"","SFotoOri":"","SGls_apellido_paterno":"tu","SGls_apellido_materno":"yo","SDv_rut":"9"},{"O_COD":1,"O_MENSAJE":"OK","NId_usuario":30,"NId_perfil":2,"NNum_rut":1,"SGls_nombre":"no","SCod_cuenta":"dimeyo","SCod_password":"dimetu","SFoto":"","SFotoOri":"","SGls_apellido_paterno":"mb","SGls_apellido_materno":"re","SDv_rut":"9"}]</string>
How can i read that response from android?
Android has built-in capabilities of manipulating JSON through the classes of the package org.json: http://developer.android.com/reference/org/json/package-summary.html
If you, instead, want to create a List of Usuario objects, in these cases, I usually use something like Jackson http://jackson.codehaus.org/ or gson https://code.google.com/p/google-gson/
In both cases you have to create a Java Bean, i.e. a class Usuario.java with all the fields private and all the getters and setters public, such as:
public class User {
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() { return name; }
}
and you can deserialise, using jackson with:
String string = [{"name": "nameA"}, {"name":"nameB"}];
ObjectMapper mapper = new ObjectMapper();
Usuario[] usuarios = mapper.fromString(string, User[].class);
In your case you should first remove the first line.

Categories