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);
Related
I am new to use gson.
I found a lots of tutorial there I can learn of gson but there are using recylerview and model file.
JsonObjectRequest request = new JsonObjectRequest(LoginUrl, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG , String.valueOf(response));
try {
String statusObject = response.getString("status");
String msgObject = response.getString("msg");
if (statusObject.equals("200")) {
JSONArray jsonArray = response.getJSONArray("response");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject managerResponse= jsonArray.getJSONObject(i);
// userIdObject = managerResponse.getString("user_id");
// String nameObject = managerResponse.getString("name");
// String emailObject = managerResponse.getString("email");
// String mobileObject = managerResponse.getString("mobile");
// String postobject = managerResponse.getString("post");
// pojectObject = managerResponse.getString("project");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
}
Here I can get data from jsonrequest using volley but unable to do that same process using volley and gson. Is there any way to use gson?
Thank You.
Update
My JSON Response
{
"status": "200",
"msg": "Successfully",
"response": [
{
"user_id": "1",
"name": "HEMANT OJHA",
"email": "hemguna#gmail.com",
"mobile": "9584919991",
"address1": "C92, PALLAWI NAGAR BABADIYA KALAN",
"user": "admin",
"api_token": "admin"
}
]
}
Generating POJO class from JSON
// Considering your response consists of json objects & json array
// Create a POJO class for your response with the link above
{
"keyOne": 1,
"keyTwo": "Some Value",
"someArray": [{
"key": "Value"
},
{
"key": "Value"
}
]
}
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class ExampleClass {
#SerializedName("keyOne")
#Expose
private int keyOne;
#SerializedName("keyTwo")
#Expose
private String keyTwo;
#SerializedName("someArray")
#Expose
private List<SomeArray> someArray = null;
public int getKeyOne() {
return keyOne;
}
public void setKeyOne(int keyOne) {
this.keyOne = keyOne;
}
public String getKeyTwo() {
return keyTwo;
}
public void setKeyTwo(String keyTwo) {
this.keyTwo = keyTwo;
}
public List<SomeArray> getSomeArray() {
return someArray;
}
public void setSomeArray(List<SomeArray> someArray) {
this.someArray = someArray;
}
}
// Parsing JSON response with GSON
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
ExampleClass resultObj = gson.fromJson(jsonObject.toString(), ExampleClass.class);
int keyOneValue = resultObj.getKeyOne() // First JSON Object
// Getting String value
String keyTwoValue = resultObj.getKeyTwo() // Second JSON Object
List<SomeArray> yourJSONArray = resultObj.getSomeArray() // Getting JSON Array contents
// Depending on JSON response that you've updated in your question
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
ExampleClass resultObj = gson.fromJson(jsonObject.toString(),ExampleClass.class);
String status = resultObj.getStatus();
String msg = resultObj.getMsg();
List<Response> responseList = resultObj.getResponse();
The best way to use for entire app is create a Utils class and use it for conversion.
GsonUtils.java
// This Class is useful for mapping Json into Java Objects and vice versa.
public class GsonUtils {
private static final Gson gson = new Gson();
// This will Convert Java Objects into JSON String...
public static String toGson(Object object) {
return gson.toJson(object);
}
// Gives Java Objects from JSON
public static <T> T fromGson(String json, Class<T> type) {
return gson.fromJson(json, type);
}
public static JsonArray fromGson(String json) {
return new JsonParser().parse(json).getAsJsonArray();
}
}
Now convert any json to and from POJO via,
POJO pojoObj = GsonUtils.toGson(POJO.class);
Try this
JSON response
String str = new Gson().toJson(response)
I am trying to build a json string in java but I am a bit confused as how I should go about it. This is what I tried so far.
String jsonString = new JSONObject()
.put("JSON1", "Hello World!")
.put("JSON2", "Hello my World!")
.put("JSON3", new JSONObject()
.put("key1", "value1")).toString();
System.out.println(jsonString);
The output is :
{"JSON2":"Hello my World!","JSON3":{"key1":"value1"},"JSON1":"Hello World!"}
The Json I want is as follows :-
{
"data":{
"nightclub":["abcbc","ahdjdjd","djjdjdd"],
"restaurants":["fjjfjf","kfkfkfk","fjfjjfjf"],
"response":"sucess"
}
}
How should I go about it?
You will need to use JSONArray and JsonArrayBuilder to map these json arrays.
This is the code you need to use:
String jsonString = new JSONObject()
.put("data", new JSONObject()
.put("nightclub", Json.createArrayBuilder()
.add("abcbc")
.add("ahdjdjdj")
.add("djdjdj").build())
.put("restaurants", Json.createArrayBuilder()
.add("abcbc")
.add("ahdjdjdj")
.add("djdjdj").build())
.put("response", "success"))
.toString();
You can use gson lib.
First create pojo object:
public class JsonReponse {
private Data data;
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
public class Data {
private String reponse;
private List<String> nightclub;
private List<String> restaurants;
public String getReponse() {
return reponse;
}
public void setReponse(String reponse) {
this.reponse = reponse;
}
public List<String> getNightclub() {
return nightclub;
}
public void setNightclub(List<String> nightclub) {
this.nightclub = nightclub;
}
public List<String> getRestaurants() {
return restaurants;
}
public void setRestaurants(List<String> restaurants) {
this.restaurants = restaurants;
}
}
}
and next complite data and generate json:
JsonReponse jsonReponse = new JsonReponse();
JsonReponse.Data data = jsonReponse.new Data();
data.setReponse("sucess");
data.setNightclub(Arrays.asList("abcbc","ahdjdjd","djjdjdd"));
data.setRestaurants(Arrays.asList("fjjfjf","kfkfkfk","fjfjjfjf"));
jsonReponse.setData(data);
Gson gson = new Gson();
System.out.println(gson.toJson(jsonReponse));
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();
}
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);
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