Hi i am getting Json Response Body from a get request in REST request.
{
"outputData": {
"data": {
"leaveList": [
{
"leaveTypeID": 1,
"leaveBalance": 2
},
{
"leaveTypeID": 2,
"leaveBalance": 9
}
]
}
}
}
I want to get leaveBalance of leaveType 2.
Index of the leaveTypeID keep changing.
Thanks
You can do it by iterating through leaveList JsonArray.
Response response = given()
.when()
.get("URL")
.then()
.extract()
.response();
int leaveTypeId = 2; // You can change this get the required leaveBalance
int leaveBalance = 0;
JSONObject responseObject = new org.json.JSONObject(response.body().asString());
JSONObject object1 = responseObject.getJSONObject("outputData");
JSONObject dataObject = object1.getJSONObject("data");
JSONArray jsonArray = dataObject.getJSONArray("leaveList");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
if (jsonObject.get("leaveTypeID").equals(leaveTypeId)) {
leaveBalance = Integer.parseInt(jsonObject.get("leaveBalance").toString());
}
}
System.out.println("leaveBalance = " + leaveBalance);
This will print;
leaveBalance = 9
You can assign values dynamically to leaveTypeId and get the leaveBalance you want.
You can use jackson-databind library for converting json string to object. I used maven package manager to add into my project.
I suggest the following solution to provide a well structure in your project. In my solution I used classes to keep json values. You can use Json To Pojo to generate objects from json string.
The output : 9
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
public class RestAssuredDemo {
public static void main(String[] args) {
String json = """
{
"outputData": {
"data": {
"leaveList": [
{
"leaveTypeID": 1,
"leaveBalance": 2
},
{
"leaveTypeID": 2,
"leaveBalance": 9
}
]
}
}
}
""";
ObjectMapper om = new ObjectMapper();
Root root = null;
try {
root = om.readValue(json, new TypeReference<Root>() {});
for (LeaveList leave: root.outputData.data.leaveList) {
if(leave.leaveTypeID == 2) {
System.out.println(leave.leaveBalance);
}
}
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
public static class LeaveList{
public int leaveTypeID;
public int leaveBalance;
}
public static class Data{
public List<LeaveList> leaveList;
}
public static class OutputData{
public Data data;
}
public static class Root{
public OutputData outputData;
}
}
GroovyPath = "outputData.data.leaveList.find{it.leaveTypeID==2}.leaveBalance"
String leaveBalance = response.extract().jsonPath().getString("outputData.data.leaveList.find{it.leaveTypeID==2}.leaveBalance");
it will provide you the leave balance of where leaveTypeID is 2 index of this object can be anywhere this will work.
Related
I have some problem fetching info from JSON. I'm confused about whether to use ArrayList or any other data type to retrieve data from JSON server.
I've tried to fetch data using
ArrayList<String>
in model.
Below is data format of JSON
[
{
"sun_timing": "{\"sun_from\":\"12:30\",\"sun_to\":\"4:30\"}",
"mon_timing": "{\"mon_from\":\"3:00\",\"mon_to\":\"4:30\"}"
},
{
"sun_timing": "{\"sun_from\":\"12:30\",\"sun_to\":\"4:30\"}",
"mon_timing": "{\"mon_from\":\"3:00\",\"mon_to\":\"4:30\"}"
}
]
I want to fetch all sun_timing data and mon_timing data.
That is sun_from,sun_to and mon_from,mon_to data.
Your Plain Old Java Object(POJO) for your json looks like this:
public class Example {
#SerializedName("sun_timing")
#Expose
private String sunTiming;
#SerializedName("mon_timing")
#Expose
private String monTiming;
public String getSunTiming() {
return sunTiming;
}
public void setSunTiming(String sunTiming) {
this.sunTiming = sunTiming;
}
public String getMonTiming() {
return monTiming;
}
public void setMonTiming(String monTiming) {
this.monTiming = monTiming;
}
}
See also: https://stackoverflow.com/a/40973753/10452701 for more details about How to get json via Rerofit2.
try this out working for me
private List<String> getSunList() {
ArrayList sunList = new ArrayList<String>()
String sun_json = your_json_string
try {
JSONObject jsonObject = new JSONObject(sun_json)
Log.d(TAG, "jsonObject: "+jsonObject)
Log.d(TAG, "jsonObject: "+sun_json)
JSONArray jsonArray = jsonObject.getJSONArray("sun_timing")
for (i in 0 until jsonArray.length())
{
JSONObject obj = jsonArray.get(i) as JSONObject
String sun_from = obj.getString("sun_from")
String sun_to = obj.getString("sun_to")
sunList.add(sun_from)
Log.d(TAG, "obj= "+obj)
}
}
catch (e: java.lang.Exception)
{
}
return sunList
}
I ultimately want to create inverted indexes using my JSON dataset. I know how to parse through one JSON object but how can I iterate through many? Here is what I have working:
File1:
{
"doc_id": "2324jos",
"screen_name": "twitter_user101",
"tweet_text": "Its a beautiful day to be productive",
"hashtags": "[]",
"links": "[]",
"place_type": "city",
"place_name": "Evergreen Park",
"created_at": "2019-02-08 22:24:03"
}
My code:
public class ParseJson {
public static void main(String[] args) throws Exception {
// this is the key object to convert JSON to Java
Tweet tweet;
ObjectMapper mapper = new ObjectMapper();
try {
File json = new File("test.json");
tweet = mapper.readValue(json, Tweet.class);
System.out.println("Java object created from JSON String :");
System.out.println(tweet);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public class Tweet {
public String doc_id;
public String screen_name;
public String tweet_text;
public String hashtags;
public String links;
public String place_type;
public String place_name;
public String created_at;
public Tweet() {
}
public Tweet(String doc_id, String screen_name, String tweet_text, String hashtags, String links, String place_type, String place_name, String created_at) {
this.doc_id = doc_id;
this.screen_name = screen_name;
this.tweet_text = tweet_text;
this.hashtags = hashtags;
this.links = links;
this.place_name = place_name;
this.place_type = place_type;
this.created_at = created_at;
}
#Override
public String toString() {
return doc_id + screen_name + tweet_text;
}
}
Now, I want to iterate through this JSON file which has 2 JSON objects in an array:
File2:
[
{
"doc_id": "2324jos",
"screen_name": "b'LIBBYRULZ'",
"tweet_text": "#ABC ya'll be lying",
"hashtags": "[]",
"links": "[]",
"place_type": "city",
"place_name": "Evergreen Park",
"created_at": "2019-02-08 22:24:03"
},
{
"doc_id": "8982hol",
"screen_name": "b'eddylee_1'",
"tweet_text": "Hungry for money",
"hashtags": "[]",
"links": "[]",
"place_type": "city",
"place_name": "Manhattan",
"created_at": "2/7/2019 17:01"
}
]
How can I adjust my above code using Jackson to do so where the doc_id is the unique key? I want to be able to return all the data in each JSON object for each doc_id.
To parse an array of JSON objects using Jackson:
Tweet[] tweets = mapper.readValue(json, Tweet[].class);
should do the trick. See below:
public class ParseJson {
public static void main(String[] args) throws Exception {
Tweet[] tweets;
ObjectMapper mapper = new ObjectMapper();
try {
File json = new File("test.json");
tweets = mapper.readValue(json, Tweet[].class);
System.out.println("Java object created from JSON String :");
Arrays.asList(tweets).forEach(System.out::println); // Prints each element in the array
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
You could try to put it in a list so you can iterate on it:
List<Tweet> data = mapper.readValue(json, new TypeReference<List<Tweet>>(){});
I would suggest using the TypeFactory to create a CollectionType and use it to parse the JSON as List<Tweet>.
CollectionType tweetListType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, Tweet.class);
List<Tweet> tweets = mapper.readValue(json, tweetListType);
tweets.forEach(System.out::println);
Here is the complete example you shared:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ParseJson {
public static void main(String[] args) {
// this is the key object to convert JSON to Java
ObjectMapper mapper = new ObjectMapper();
try {
File json = new File("test.json");
CollectionType tweetListType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, Tweet.class);
List<Tweet> tweets = mapper.readValue(json, tweetListType);
System.out.println("Java objects created from JSON String:");
tweets.forEach(System.out::println);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
This is the JSON array:
{
"server_response": [{
"Total": "135",
"Paid": "105",
"Rest": "30"
}]
}
So, how can i get the object names? I want to put them in separate TextView.
Thanks.
Put this out side everything. I mean outside onCreate() and all.
private <T> Iterable<T> iterate(final Iterator<T> i){
return new Iterable<T>() {
#Override
public Iterator<T> iterator() {
return i;
}
};
}
For getting the names of objects :
try
{
JSONObject jsonObject = new JSONObject("{" +"\"server_response\": [{" +"\"Total\": \"135\"," +"\"Paid\": \"105\"," +"\"Rest\": \"30\"" +"}]"+"}";);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
JSONObject object = jsonArray.getJSONObject(0);
for (String key : iterate(object.keys()))
{
// here key will be containing your OBJECT NAME YOU CAN SET IT IN TEXTVIEW.
Toast.makeText(HomeActivity.this, ""+key, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
Hope this helps :)
My suggestion:
Go to this website:
Json to pojo
Get your pojo classes and then use them in Android.
All you need to do is to use Gson.fromGson(params here).
One of your params is the class that you created using the online schema.
You can use jackson ObjectMapper to do this.
public class ServerResponse {
#JsonProperty("Total")
private String total;
#JsonProperty("Paid")
private String paid;
#JsonProperty("Rest")
private String rest;
//getters and setters
//toString()
}
//Now convert json into ServerResponse object
ObjectMapper mapper = new ObjectMapper();
TypeReference<ServerResponse> serverResponse = new TypeReference<ServerResponse>() { };
Object object = mapper.readValue(jsonString, serverResponse);
if (object instanceof ServerResponse) {
return (ServerResponse) object;
}
JSONObject jsonObject = new JSONObject("Your JSON");
int Total = jsonObject.getJSONArray("server_response").getJSONObject(0).getInt("Total");
int Paid = jsonObject.getJSONArray("server_response").getJSONObject(0).getInt("Paid");
int Rest = jsonObject.getJSONArray("server_response").getJSONObject(0).getInt("Rest");
Hi i am trying to iterate through a json string that looks like this:
{
"vendor":[
{
"vendor_name":"Tapan Moharana",
"vendor_description":"",
"vendor_slug":"tapan",
"vendor_logo":null,
"contact_number":null
}
],
"products":
{
"25":
{
"name":"Massage",
"price":"5000.0000",
"image":"http:\/\/carrottech.com\/lcart\/media\/catalog\/product\/cache\/1\/image\/150x\/9df78eab33525d08d6e5fb8d27136e95\/2\/9\/29660571-beauty-spa-woman-portrait-beautiful-girl-touching-her-face.jpg"
},
"26":
{
"name":"Chicken Chilly",
"price":"234.0000",
"image":"http:\/\/carrottech.com\/lcart\/media\/catalog\/product\/cache\/1\/image\/150x\/9df78eab33525d08d6e5fb8d27136e95\/c\/h\/cheicken.jpg"
},
"27":
{
"name":"Chicken Biryani",
"price":"500.0000",
"image":"http:\/\/carrottech.com\/lcart\/media\/catalog\/product\/cache\/1\/image\/150x\/9df78eab33525d08d6e5fb8d27136e95\/placeholder\/default\/image_1.jpg"
}
}
}
here is a better view of the json string:
I am iterating through the vendor array of this json string using this code:
JSONObject jsono = new JSONObject(response);
JSONArray children = jsono.getJSONArray("vendor");
for (int i = 0; i <children.length(); i++) {
JSONObject jsonData = children.getJSONObject(i);
System.out.print(jsonData.getString("vendor_name") + "<----");
// String vendorThumbNailURL=jsonData.getString("")
//jvendorImageURL.setImageUrl(local, mImageLoader);
vendorLogo=vendorLogo+jsonData.getString("vendor_logo").trim();
jvendorImageURL.setImageUrl(vendorLogo, mImageLoader);
jvendorName.setText(jsonData.getString("vendor_name"));
jvendorAbout.setText(jsonData.getString("vendor_description"));
jvendorContact.setText(jsonData.getString("contact_number"));
}
but I dont know how to get data from the "products" object please help me how do i set my json objects to iterate through "products"
when i try to change the format of the array so that both products and vendor are a separate json array i still get the above json format..
this is what i am doing
$resp_array['vendor'] = $info;
$resp_array['products'] = $vendorProductsInfo;
$resp_array = json_encode($resp_array);
print_r($resp_array);
please help me with this
MODIFIED QUESTION:
I have modified my web response like this:
[{"entity_id":24,"product_name":"Burger","product_image_url":"\/b\/u\/burger_large.jpg","price":"234.0000","category_id":59},{"entity_id":27,"product_name":"Chicken Biryani","product_image_url":"\/b\/i\/biryani.jpg","price":"500.0000","category_id":59},{"entity_id":31,"product_name":"Pizza","product_image_url":"\/p\/i\/pizza_png7143_1.png","price":"125.0000","category_id":59}]
and the code:
JSONArray children = jsono.getJSONArray("vendor");
for (int i = 0; i <children.length(); i++) {
JSONObject jsonData = children.getJSONObject(i);
System.out.print(jsonData.getString("vendor_name") + "<----");
// String vendorThumbNailURL=jsonData.getString("")
//jvendorImageURL.setImageUrl(local, mImageLoader);
vendorLogo=vendorLogo+jsonData.getString("vendor_logo").trim();
jvendorImageURL.setImageUrl(vendorLogo, mImageLoader);
jvendorName.setText(jsonData.getString("vendor_name"));
jvendorAbout.setText(jsonData.getString("vendor_description"));
jvendorContact.setText(jsonData.getString("contact_number"));
System.out.print(jsonData.getString("products") + "<----");
}
JSONObject jsono1 = new JSONObject(response);
JSONArray childrenProducts = jsono1.getJSONArray("products");
for(int i=0;i<childrenProducts.length();i++){
JSONObject jsonData = childrenProducts.getJSONObject(i);
System.out.print(jsonData.getString("name") + "<----dd");
}
but still the products part is not working... please help
Here is the working solution: Using GOOGLE GSON (Open source jar)
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class JsonToJava {
public static void main(String[] args) throws IOException {
try{
String json = "<YOUR_JSON>";
Gson gson = new GsonBuilder().create();
VendorInfo vInfo = gson.fromJson(json, VendorInfo.class);
System.out.println(vInfo.getVendorName());
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
Create classes for Vendor and Product
public class Vendor {
public String vendor_name;
public String vendor_description;
public String vendor_slug;
public String vendor_logo;
public String contact_number;
public String getName() {
return vendor_name;
}
}
public class Product {
public String name;
public long price;
public String image;
public String getName() {
return name;
}
}
VendorInfo is the JSON object form:
import java.util.Map;
public class VendorInfo {
public Vendor[] vendor;
public Map<Integer, Product> products;
public String getVendorName() {
return vendor[0].getName();
}
public Product getProduct() {
System.out.println(products.size());
return products.get(25);
}
}
You can add your getters for Vendor, Product and VendorInfo. You are done! You will get all the data.
Output of JsonToJava:
Tapan Moharana
To get your products data , you need to use Iterator
JSONObject jProducts = jsonObject
.optJSONObject("products");
try {
if (jProducts
.length() > 0) {
Iterator<String> p_keys = jProducts
.keys();
while (p_keys
.hasNext()) {
String keyProduct = p_keys
.next();
JSONObject jP = jProducts
.optJSONObject(keyProduct);
if (jP != null) {
Log.e("Products",
jP.toString());
}
}
}
} catch (Exception e) { // TODO:
// handle
// exception
}
you can try with this
JSONObject jsono = null;
try {
jsono = new JSONObject(response);
JSONObject productObject = jsono.getJSONObject("products");
Iterator<String> keys = productObject.keys();
while (keys.hasNext())
{
// get the key
String key = keys.next();
// get the value
JSONObject value = productObject.getJSONObject(key);
//get seprate objects
String name = value.getString("name");
String image = value.getString("image");
Log.i(TAG,name+"-"+image);
}
}
catch (JSONException e) {
e.printStackTrace();
}
Try this :
JSONObject productObject = jsono.getJSONObject("products");
JSONObject json_25 = productObject getJSONObject("25");
String name_25= json_25.getString("name");
String price_25= json_25.getString("price");
String image_25= json_25.getString("image");
JSONObject json_26 = productObject getJSONObject("26");
String name_26= json_26.getString("name");
String price_26= json_26.getString("price");
String image_26= json_26.getString("image");
JSONObject json_27 = productObject getJSONObject("27");
String name_27= json_27.getString("name");
String price_27= json_27.getString("price");
String image_27= json_27.getString("image");
I'm trying to read JSON file in Java (I'm starting with JSON).
The JSON file:
[
{
"idProducto":1,
"Nombre":"Coca Cola",
"Precio":0.9,
"Cantidad":19
},
{
"idProducto":2,
"Nombre":"Coca Cola Zero",
"Precio":0.6,
"Cantidad":19
},
[....]
]
I tried the following:
ArrayList<Dispensador> Productos = new ArrayList<Dispensador>();
FileReader reader = new FileReader(new File("productos.json"));
JSONParser jsonParser = new JSONParser();
JSONArray jsonArray = (JSONArray) jsonParser.parse(reader);
JSONObject object = (JSONObject) jsonArray.get(0);
Long idProducto = (Long) object.get("idProducto");
JSONArray nombres = object.getJSONArray("idProducto");
Iterator i = jsonArray.iterator();
while (i.hasNext()) {
String nombre = (String) object.get("Nombre");
Double precio = (Double) object.get("Precio");
BigDecimal precioB = new BigDecimal(precio);
Long cantidad = (Long) object.get("Cantidad");
int cantidadB = toIntExact(cantidad);
System.out.println(nombre);
Productos.add(new Dispensador(nombre, precioB, cantidadB));
}
But enters into loop. Also I tried with a for loop, but no luck.
Thanks!
You can use gson library
You can use Maven or jar file: http://mvnrepository.com/artifact/com.google.code.gson/gson
package com.test;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class AppJsonTest {
public static void main(String[] args) {
List<DataObject> objList = new ArrayList<DataObject>();
objList.add(new DataObject(1, "Coca Cola", 0.9, 19));
objList.add(new DataObject(2, "Coca Cola Zero", 0.6, 19));
// Convert the object to a JSON string
String json = new Gson().toJson(objList);
System.out.println(json);
// Now convert the JSON string back to your java object
Type type = new TypeToken<List<DataObject>>() {
}.getType();
List<DataObject> inpList = new Gson().fromJson(json, type);
for (int i = 0; i < inpList.size(); i++) {
DataObject x = inpList.get(i);
System.out.println(x.toString());
}
}
}
class DataObject {
int idProducto;
String Nombre;
Double Precio;
int Cantidad;
public DataObject(int idProducto, String nombre, Double precio, int cantidad) {
this.idProducto = idProducto;
Nombre = nombre;
Precio = precio;
Cantidad = cantidad;
}
public int getIdProducto() {
return idProducto;
}
public void setIdProducto(int idProducto) {
this.idProducto = idProducto;
}
public String getNombre() {
return Nombre;
}
public void setNombre(String nombre) {
Nombre = nombre;
}
public Double getPrecio() {
return Precio;
}
public void setPrecio(Double precio) {
Precio = precio;
}
public int getCantidad() {
return Cantidad;
}
public void setCantidad(int cantidad) {
Cantidad = cantidad;
}
#Override
public String toString() {
return "DataObject [idProducto=" + idProducto + ", Nombre=" + Nombre + ", Precio=" + Precio + ", Cantidad=" + Cantidad + "]";
}
}
Use gson library to read and write json:
try {
JsonReader reader = new JsonReader(new FileReader("json_file_path.json"));
reader.beginArray();
while (reader.hasNext()) {
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("idProducto")) {
System.out.println(reader.nextInt());
} else if (name.equals("Nombre")) {
System.out.println(reader.nextString());
} else if (name.equals("Precio")) {
System.out.println(reader.nextDouble());
} else if (name.equals("Cantidad")) {
System.out.println(reader.nextInt());
} else {
reader.skipValue();
}
}
reader.endObject();
}
reader.endArray();
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
download http://www.java2s.com/Code/JarDownload/gson/gson-2.2.2.jar.zip
You are testing whether the iterator has a next element with i.hasNext(). But you don't consume (or retrieve) this next element by i.next() which is typically in the first statement of the looped block. Therefore i.hasNext() will return true forever.
EDIT: You probably want to set object to i.next() because in your code snippet it always remains at the 0's element you assigned before the loop.
There are many open source libraries, present to parse json to object or just to read and write json values. If you want to read and write json then you can use org.json library.
Use org.json library to parse it and create JsonObject :-
JSONObject jsonObj = new JSONObject(<jsonStr>);
Now, use this object to get your values :-
String id = jsonObj.getString("pageInfo");
You can see complete example here :-
How to parse Json in java
If you want to parse your json to particular POJO and then use that pojo to get values, then use jackson-databind library, this will parse your json to POJO class :-
ObjectMapper mapper = new ObjectMapper();
book = mapper.readValue(json, Book.class);
You can see complete example here, How to parse json in java