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)
Related
I am using below code to automate REST API.
Please help me to understand how can I put whole json data for sample data mentioned below as the input has arrays whereas till now I used flat jsons without arrays
Method Dummy()
{
RestAssured.baseURI ="http://mydummyURL";
RequestSpecification request = RestAssured.given();
JSONObject requestParams = new JSONObject();
requestParams.put("id", "THAILAND"); //Issue is with this code
request.header("Content-Type", "application/json");
request.body(requestParams.toJSONString());
Response response = request.post("/EndPoint");
}
where the json body looks like this
{
"tag1": "value1",
"tag2": "value2",
"tag3": {
"tag31": "value31",
"tag32": "value32"
},
"tag4": [{
"domainName": "ABC",
"domainId": "123ABC123",
"domainGUID": "TestMyDomain"
},
{
"domainName": "XYZ",
"domainId": "123XYZ123",
"domainGUID": "TestMyDomain"
}
]
}
ArrayList<JSONObject> array= new ArrayList<JSONObject>();
JSONObject json= new JSONObject();
try {
json.put("key", "value");// your json
} catch (JSONException e) {
e.printStackTrace();
}
array.add(json);
String printjsonarray= array.toString();// pass this into the request
ObjectMapper mapper = new ObjectMapper();
//Create a Java Class for the variables inside array.
JsonArrayData tag4paramVal1 = new JsonArrayData("ABC","123ABC123","TestMyDomain");
JsonArrayData tag4paramVal2 = new JsonArrayData("XYZ","123XYZ123","TestMyDomain");
Object[] tag4ValArray = {tag4paramVal1,tag4paramVal2};
String reqJson = null;
List<String> tag4Data = new ArrayList<String>();
for(Object obj:tag4ValArray){
reqJson = mapper.writeValueAsString(obj);
System.out.println(reqJson);
tag4Data.add(reqJson);
}
System.out.println(tag4Data);
HashMap<String,List<String>> finalReq = new HashMap<String,List<String>>();
finalReq.put("\"tag4\":",tag4Data);
String finalreqString = finalReq.toString();
System.out.println(finalreqString);
finalreqString = finalreqString.replace('=', ' ');
System.out.println(finalreqString);
//Use the above String as a parameter to POST request. You will get your desired JSON array .
//JsonArrayData class code
public class JsonArrayData {
String domainName;
String domainId;
String domainGUID;
public JsonArrayData(String domainName,String domainId,String domainGUID){
this.domainName = domainName;
this.domainId = domainId;
this.domainGUID = domainGUID;
}
public String getDomainName() {
return domainName;
}
public void setDomainName(String domainName) {
this.domainName = domainName;
}
public String getDomainId() {
return domainId;
}
public void setDomainId(String domainId) {
this.domainId = domainId;
}
public String getDomainGUID() {
return domainGUID;
}
public void setDomainGUID(String domainGUID) {
this.domainGUID = domainGUID;
}
}
I like to know how I might do the following:
I want to create a json format of the following:
I want to be able to create a recursive function that takes an object holding a list of other objects of the same type and in a method to recursively create the format below.
{
"name": "lib",
"contains": [{
"name": "room",
"contains": [{
"name": "bookshelf",
"contains": [{
"name": "shelf",
"contains": []
}]
}]
}]
}
I have this as the following method:
private JSONObject json = new JSONObject();
public JSONObject setupLib(Contains contain) {
int count = contain.getContainerList().size();
for(int i = 0; i < count; i++){
try {
json.put("name", contain.getContainerList().get(i).getContainerName());
if(contain.getContainerList().size() != 0) {
Contains contains = (Contains) contain.getContainerList().get(i);
JSONArray array = new JSONArray();
json.put("contain",array.put(setupLib(contains)));}
}catch (JSONException e){
Log.i(Tag, e.getMessage());
}
}
return json;
}
I get a stackoverflow on the array/object
Two options
Do it yourself recursively
Use a library such as Gson to save you the development time and effort
Since this is a learning experience, I have shown both that return this JSON.
{
"name": "lib",
"contains": [{
"name": "room",
"contains": [{
"name": "bookshelf",
"contains": [{
"name": "shelf",
"contains": []
}]
}]
}]
}
public static void main(String[] args) {
Contains lib = new Contains("lib");
Contains room = new Contains("room");
Contains bookshelf = new Contains("bookshelf");
Contains shelf = new Contains("shelf");
bookshelf.add(shelf);
room.add(bookshelf);
lib.add(room);
// Option 1
System.out.println(setupLib(lib).toJSONString());
// Option 2
Gson gson = new Gson();
System.out.println(gson.toJson(lib));
}
private static JSONObject setupLib(Contains contain) {
if (contain == null) return null;
LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();
JSONArray array = new JSONArray();
for (Contains c : contain.getContainerList()) {
JSONObject innerContain = setupLib(c);
if (innerContain != null) {
array.add(innerContain);
}
}
map.put("name", contain.getName());
map.put("contains", array);
return new JSONObject(map);
}
This is the model object, for reference
public class Contains {
#SerializedName("name")
#Expose
private String name;
#SerializedName("contains")
#Expose
private List<Contains> contains;
public Contains(String name) {
this.name = name;
contains = new ArrayList<Contains>();
}
public void setName(String name) {
this.name = name;
}
public void add(Contains c) {
this.contains.add(c);
}
public void setContainerList(List<Contains> contains) {
this.contains = contains;
}
public String getName() {
return name;
}
public List<Contains> getContainerList() {
return this.contains;
}
}
I think is far easier if you'd serialize both the JSONObject and Contains classes. This way you'll be able to use the Jackson library to create the JSON file for you.
You can find more information about the Jackson library on the following GitHub page: https://github.com/FasterXML/jackson.
im trying to have my app connect to a rest API and pull the data from it. Ive so far pulled the data . but i dont know how to parse it. i believe thats what you do next.
here a snippet of my code that conencts to my rest API and gets the data . the error i get is JSONArray cannot be converted to JSONObject
if (status == 200) {
InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String responseString;
StringBuilder sb = new StringBuilder();
while ((responseString = reader.readLine()) != null) {
sb = sb.append(responseString);
}
String speciesListData = sb.toString();
species= SpeciesJson.fromJson(speciesListData);
Log.d(Constants.TAG, "speciesJSON: " + species);
return true;
}
this is were i tried to parse it , it was working fine up until here. hers is the line were i try to parse it
species= SpeciesJson.fromJson(speciesListData);
and this thats were it broke lol
public class SpeciesJson {
private String scientific_name, name,description;
public SpeciesJson (JSONObject species) throws JSONException {
this.scientific_name=species.optString("scientific_name");
this.name=species.optString("name");
this.description=species.optString("description");
}
public static ArrayList<SpeciesJson> fromJson(String photoData) throws JSONException {
ArrayList<SpeciesJson> speciesData = new ArrayList<>();
JSONObject data = new JSONObject(photoData);
JSONObject photos = data.optJSONObject("name");
JSONArray photoArray = photos.optJSONArray("name");
for (int i = 0; i < photoArray.length(); i++) {
JSONObject photo = (JSONObject) photoArray.get(i);
SpeciesJson currentPhoto = new SpeciesJson(photo);
speciesData.add(currentPhoto);
}
return speciesData;
}
so when i run it using the parsing method i made, it doesnt not work.
the sample of hte json data is below, im trying to show the scientific_name and name in a view
{
"id": 1,
"scientific_name": "Platanus racemosa",
"name": "California Sycamore",
"description": "typically in river areas, but planted all throughout L.A",
"type": 1
},
{
"id": 2,
"scientific_name": "Pyrus kawakamii",
"name": "Ornamental Pear",
"description": "native to Asia, commonly planted in L.A",
"type": 1
},
{
"id": 3,
"scientific_name": "Liquidambar styraciflua",
"name": "American Sweetgum",
"description": "native to SE U.S, planted all around L.A",
"type": 1
},
{
"id": 4,
"scientific_name": "Setophaga coronata",
"name": "Yellow-rumped Warbler",
"description": "native bird, spends the winter in L.A before migrating north during the summer to breed",
"type": 2
},
{
"id": 5,
"scientific_name": "Calypte anna",
"name": "Anna's Hummingbird",
"description": "native bird, does not migrate. Spends the year in L.A",
"type": 2
},
{
"id": 6,
"scientific_name": "Regulus calendula",
"name": "Ruby-crowned Kinglet",
"description": "native bird, spends the winter in L.A before migrating north during the summer to breed",
"type": 2
}
]
My Dear Friend Use googles GSON Library that's it.
And For Your Help I made this little bit easier.
Make This Class SpeciesJson.java
public class SpeciesJson {
private String scientific_name;
private String name;
private String description;
public SpeciesJson() {
}
public SpeciesJson(String scientific_name,String name,String description) {
this.scientific_name = scientific_name;
this.name = name;
this.description = description;
}
//And getter,setters
}
If SpeciesJson Is simple an object then use this
Gson gson = new Gson();
SpeciesJson species = gson.fromJson(responseString,SpeciesJson.class);
If SpeciesJson Is an ArrayList then use this (Its Looks Like Your Case So Check This As Your Json Response Consist Multiple SpeciesJson Objects)
Gson gson = new Gson();
ArrayList<SpeciesJson> species = new ArrayList<>();
SpeciesJson[] speciesarray = (SpeciesJson[]) gson.fromJson(responseString,SpeciesJson[].class);
Collections.addAll(species, speciesarray);
And If You wanna learn something more about Gson Library check this link
https://guides.codepath.com/android/Leveraging-the-Gson-Library
Well you can use GSON to parse the data and Volley to get the data.
//Create volley request
String url = String.format("SOME_URL", arrayOfObject);
RequestQueue queue = VolleyService.getInstance(this.getContext()).getRequestQueue();
StringRequest request = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// we got the response, now our job is to handle it
try {
ArrayList<SpeciesJson> speciesData = getDataFromJson(stream);
} catch (RemoteException | OperationApplicationException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//something happened, treat the error.
Log.e("Error", error.toString());
}
});
queue.add(request);
//If your JSON data is an Array
private static List<SpeciesJson> getDataFromJson(String json) {
Gson gson = new GsonBuilder().create();
List<SpeciesJson> result = new ArrayList<>();
try {
JSONObject posts=new JSONObject(json);
JSONArray dataArray=posts.getJSONArray("data");
for(int n = 0; n < dataArray.length(); n++)
{
JSONObject object = dataArray.getJSONObject(n);
result.add(gson.fromJson(object.toString(), SpeciesJson.class));
}
} catch (JSONException e) {
e.printStackTrace();
}
return result;
}
And volley Service
public class VolleyService {
private static VolleyService instance;
private RequestQueue requestQueue;
private ImageLoader imageLoader;
private VolleyService(Context context) {
requestQueue = Volley.newRequestQueue(context);
imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap> cache = new LruCache<String, Bitmap>(20);
#Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url,bitmap);
}
});
}
public static VolleyService getInstance(Context context) {
if (instance == null) {
instance = new VolleyService(context);
}
return instance;
}
public RequestQueue getRequestQueue() {
return requestQueue;
}
public ImageLoader getImageLoader() {
return imageLoader;
}
}
Or you can use Retrofit library to parse it for you:
http://www.vogella.com/tutorials/Retrofit/article.html
https://github.com/codepath/android_guides/wiki/Consuming-APIs-with-Retrofit
You should use retrofit library with GsonConverterFactory. The best solution to manage network response.
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonElement obj = parser.parse(Tempx.getString("GSON_FEED","")).getAsJsonObject();
for(JsonElement jsx: obj) {
MainPojo cse = gson.fromJson(jsx, MainPojo.class);
TweetList.add(cse);
Log.w("F:", "" + TweetList.get(0).getStatuses().get(0).getScreenName());
}
Trying to store JsonObjects into an ArrayList, however I get an error in the line under obj
for(JsonElement jsx: obj)
saying
foreach not applicable to type 'com.google.gson.JsonElement
How to fix this?
you can easily read JSONArray into ArrayList of type class to which JSONArray is representing. Thank is GSON this entire process can be done in a single line of code. as shown bellow.
ArrayList<MyItem> items2 = (new Gson()).fromJson(result,new TypeToken<ArrayList<MyItem>>() {}.getType());
Lets assume you are given with a JSONArray of type MyItem above line of code will convert JSONArray into the ArrayList of type MyItem.
I have written a sample code, that you may get a better picture.
import java.util.ArrayList;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class MyTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<MyItem> items = new ArrayList<>();
for (int i = 0; i < 5; i++) {
MyItem item = new MyItem();
item.setRate("rate_"+i);
item.setSomeCode("some_"+i);
items.add(item);
}
String result = (new Gson()).toJson(items);
System.out.println(""+result);
ArrayList<MyItem> items2 = (new Gson()).fromJson(result,new TypeToken<ArrayList<MyItem>>() {}.getType());
System.out.println(""+items2.size());
}
}
class MyItem {
private String rate;
private String someCode;
public String getRate() {
return rate;
}
public void setRate(String rate) {
this.rate = rate;
}
public String getSomeCode() {
return someCode;
}
public void setSomeCode(String someCode) {
this.someCode = someCode;
}
}
Output
[
{
"rate": "rate_0",
"someCode": "some_0"
},
{
"rate": "rate_1",
"someCode": "some_1"
},
{
"rate": "rate_2",
"someCode": "some_2"
},
{
"rate": "rate_3",
"someCode": "some_3"
},
{
"rate": "rate_4",
"someCode": "some_4"
}
]
this JSONArray is converted into ArrayList of type MyItem
I have also written some answers on this topic which you may want to check for further information on serialization and de-serialization using GSON library
Example_1
Example_2
Example_3
Example_4
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);