Display certain items from array of objects in recyclerview - json

From the code below, I want to display request_id, request_title, status, no of trucks in recyclerview using retrofit 2.0. How to do this?
Here is my nested array of objects.
[
{
"id": 96,
"request_id": 24365,
"request_title": "tsfghjjlfdsg;lhj",
"transport_co_id": 1,
"status": 1,
"truck_info": [
{
"driver_mobile": 2147483647,
"driver_name": "dsdsd",
"truck_no": 1111
},
{
"driver_mobile": 2147483647,
"driver_name": "add",
"truck_no": 727
}
]
},
{
"id": 97,
"request_id": "test123",
"request_title": "test title",
"transport_co_id": 1,
"status": 1,
"truck_info": [
{
"driver_mobile": 2147483647,
"driver_name": "dsdsd",
"truck_no": 1111
},
{
"driver_mobile": 2147483647,
"driver_name": "add",
"truck_no": 1
}
]
}
]

create retrofit interface , class
public class ChampApiClient {
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}

Related

Converting JSON to POJO class

I have been struggling with converting the below json .
Is the data class should be mapped as Map<String,Object>.Then use Object mapper class to all values?What is the best way to map below pojo
Json Response
{
"data": {
"Order": [
{
{
"Property1" : Number1
"Propery2": Number 2
},
"Lines": [
{
"Id": "123456",
"itemDescription": "Green glass",
}
],
"date": "",
"updateDate": ""
}
]
}
}
Data class:
#JsonIgnoreProperties(ignoreUnknown = true)
public class Details {
public Map<String,Object> data;
}

Is there any way to manipulate json response in spring boot?

My project is about a shopping application build with Spring boot. When I get the shopping cart from the endpoint. It will return JSON like this
{
"shoppingCartCode": 2,
"productDetailList": [
{
"productDetailCode": 5,
"price": 21000.0,
"dateManufacture": "2021-09-23",
"quantity": 10,
"colorName": "Pink",
"warranty": 2,
"product": {
"prodCode": 2,
"prodName": "Z Flod 10",
"description": "Z Flod 10 Flippable then Break up",
"brand": {
"brandName": "Samsung",
"imageList": []
},
"shop": {
"shopCode": 5,
"shopName": "Montri Phone",
"shopDescription": "Strict security",
"type": "SELLER",
"imageList": []
}
},
"imageList": [
{
"imageName": "i-agree.png"
},
{
"imageName": "i-agree1.png"
},
{
"imageName": "i-agree2.png"
},
{
"imageName": "i-agree3.png"
}
]
}
]
}
I want to manipulate the imageList to like this
"imageList": ["i-agree.png","i-agree1.png","i-agree2.png","i-agree3.png"]
Is there any way to manipulate JSON before response?
or it might need POJO to wrap it up before response again?
You can achieve this with a custom serializer as follows:
public class ImageListConverter extends StdConverter<List<Image>, List<String>> {
#Override
public List<String> convert(List<Image> images) {
return images.stream().map(User::getImageName).collect(Collectors.toList());
}
}
Now you just need to annotate the imageList property:
public class ProductDetail {
#JsonSerialize(converter = ImageListConverter.class)
List<Image> imageList;
}
The other option would be changing List<Image> to List<String> and do the conversion when creating ProductDetail. It really depends on how you use ProductDetail elsewhere.

Getting a value from a complex JSON file (multiple objects inside an object)

I am trying to get a value from a JSON file, however it is a complex JSON file and i'm not sure how to go about it.
The value is situated inside an object, that is inside another object, which inside another object.
The values I want to retrieve from the JSON file is "value" and "unit" situated inside the object "metric". I have been able to successfully retrieve the "name" value.
The JSON file:
{
"ingredients": [
{
"name": "breakfast sausage",
"image": "breakfast-sausage-links.jpg",
"amount": {
"metric": {
"value": 226.796,
"unit": "g"
},
"us": {
"value": 8,
"unit": "ounces"
}
}
},
I will also include the method that I parse the JSON from:
private void jsonParse(){
String url = "https://api.spoonacular.com/recipes/"+ rMealId + "/ingredientWidget.json?&apiKey=da7dd16a704f4552b70a96c1e9641b08";
RequestQueue requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("ingredients");
for(int i = 0; i < jsonArray.length(); i++){
JSONObject ingredients = jsonArray.getJSONObject(i);
String iName = ingredients.getString("name");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Log.e("Volley", error.toString());
}
});
requestQueue.add(request);
}
Just focusing on your json string, try this:
let ings =
{
"ingredients": [
{
"name": "breakfast sausage",
"image": "breakfast-sausage-links.jpg",
"amount": {
"metric": {
"value": 226.796,
"unit": "g"
},
"us": {
"value": 8,
"unit": "ounces"
}
}
}
]
}
let jp = require('jsonpath');
let eat = jp.query(ings, '$..metric.*');
console.log(eat);
output:
[ 226.796, 'g' ]

How to get key from Observable?

I am trying to read data from firebase using angular 2 and typescript
my code
export class DashboardComponent implements OnInit {
itemsRef: AngularFireList<any>;
items: Observable<any[]>;
constructor( afDatabase: AngularFireDatabase) {
this.itemsRef = afDatabase.list('/user_orders/louro');
this.items = this.itemsRef.valueChanges();
this.items.subscribe(val_2 => {
alert(val_2.keys());
val_2.forEach(function (value2) {
{
Object.keys(value2).forEach(function(k2) {
{
// k is key
let count = Object.keys( (value2[k2] )).length;
console.log("New order key "+k2);
for(let i=0;i<count;i++){
console.log(i+"=> "+JSON.stringify (value2[k2][i]));
}
}
});
}
})
});
}
ngOnInit() {
}
}
and on val_2 only contains
[
{
"-L7rtl2NesdOYVD4-bMs": [
{
"ads_show": false,
"brand": "",
"buttonLabel": "Add to cart",
"child": "fruits",
"decrn": "testing for demonstrate",
"key": "-L7rtXc0pMQhi1ClK-pP",
"mid": "fresh fruits",
"note": "",
"orderInfo": {
"message": "nil",
"methode": "cash on delivery",
"status": "nil",
"time": 1521356314040,
"time2": 1521356254115
},
"p_id": 73,
"p_name": "testing",
"position": 0,
"primary_key": "testinglouro",
"qty": {
"m_qty": 1,
"qty": 23,
"unite": "1kg",
"user_intput_qty": 2
},
"quantity_new": 2,
"querykey_shop_name_top": "louro_fruits",
"sellerName": "louro",
"sellonline": true,
"seo": {
"meta_descrption": "",
"meta_title": ""
},
"service": false,
"serviceMessage": "Please enter your complaint details",
"serviceTitle": "Service Requesting",
"shopname": "louro",
"shopview": false,
"summery": "nil",
"tags": "",
"top": "fruits",
"uid": "IG2SxH6Gcabr3QVLz9jE9Wwweh62",
"variants": [
{
"img_position": 0,
"prize": {
"mrp": 58,
"selling_prize": 45,
"tax": 0
},
"qty": {
"m_qty": 1,
"qty": 23,
"unite": "1kg",
"user_intput_qty": 2
},
"shipping": {
"minmumbuy": 0,
"s_cost": 0,
"s_dlts": ""
}
}
],
"variants_position": 0
}
]
}
]
And my database is
I need this key "4X2NpohlbUa3AA7ri6iHGNm2If93" .How to get that key ? I tried val_2.key
but it showing error "[ts] Property 'key' does not exist on type 'any[]'. Did you mean 'keys'?"
In java i am using below code and work fine dataSnapshot1.getKey();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference(getResources().getString(R.string.user_orders)+"/"+
shop_name,getContext()));
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
// MainAction.setDefaults("OpenCategories",dataSnapshot.toString(),getActivity());
if (dataSnapshot.hasChildren()) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
orderDetails1 = null;
orderDetails1 = new OrderDetails();
if (dataSnapshot1.hasChildren()) {
int id = -1;
for (DataSnapshot dataSnapshot2 : dataSnapshot1.getChildren()) {
id = id + 1;
if (dataSnapshot2.hasChildren()) {
int productid = -1;
for (DataSnapshot dataSnapshot3 : dataSnapshot2.getChildren()) {
productid = productid + 1;
if (dataSnapshot3.hasChildren()) {
orderDetails1.productmillaList.add(dataSnapshot3.getValue(Productmilla.class));
}
orderDetails1.productmillaList.get(productid).setPosition(Integer.parseInt(dataSnapshot3.getKey()));
orderDetails1.productmillaList.get(productid).setId(dataSnapshot2.getKey());
// Log.d("key2",dataSnapshot2.getKey()+" "+productid);
}
}
//orderDetails1.productmillaList.get(id).setId(dataSnapshot2.getKey());
}
}
orderDetails1.key = dataSnapshot1.getKey();
orderDetails.add(orderDetails1);
}
getaddress(orderDetails);
} else mProgressBar.setVisibility(View.GONE);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
mProgressBar.setVisibility(View.GONE);
Log.w("dd", "Failed to read value."+ error.getMessage());
}
});
Update :
According to the updated response data, you should access using Object.keys(val)[0] which gives the value for key "4X2NpohlbUa3AA7ri6iHGNm2If93", since it is the first key.
According to older response data :
Your val is an array.
This should work.
Object.keys(val[0]).forEach(function(k1) {
{
console.log("Key first : "+ k1);
});
In your JSON, val is an array.
Object.keys(val[0])
will give you the keys of the first element of that array, which is what you're after.
TO get the first key in the Object
Object.keys(val)[0]; //returns 'first key'
[https://stackoverflow.com/a/11509718/7458082][1]
To iterate through the object
Object.keys(obj).forEach(function(key,index) {
// key: the name of the object key
// index: the ordinal position of the key within the object
});
[https://stackoverflow.com/a/11509718/7458082][1]

Jackson: JSON parsing for array of parent elements : Root name '' does not match expected ('List')

I am getting the following exception after writing the below code.
Caused by: com.fasterxml.jackson.databind.JsonMappingException: Root name 'Filing' does not match expected ('List') for type [collection type; class java.util.List, contains [simple type, class MasMonthlyReportDetail]]
JSON Object
{
"Filing":
[
{
"periodInfo":
{
"date": "06-05-2013",
"year": "2015",
"Month": "January"
},
"employerInfo":
{
"name": "Y",
"place": "Y",
"country": "N",
},
"employeeInfo":
[
{
"name": "785-23-0370",
"dob": "05/25/1952",
}
],
"messages":
[
{
"defaultMessage" : "xx",
"messageType" : "yy",
"messageCode" : "102"
}
]
},
{
"periodInfo":
{
"date": "06-05-2013",
"year": "2015",
"Month": "January"
},
"employerInfo":
{
"name": "Y",
"place": "Y",
"country": "N",
},
"employeeInfo":
[
{
"name": "785-23-0370",
"dob": "05/25/1952",
}
],
"messages":
[
{
"defaultMessage" : "xx",
"messageType" : "yy",
"messageCode" : "102"
}
]
}
]
}
Main Class
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
List<MasMonthlyReportDetail> lcd = objectMapper.readValue(new File(filePath),new TypeReference<List<MasMonthlyReportDetail>>(){});
MasMonthlyReportDetail.java
#JsonRootName(value="Filing")
public class MasMonthlyReportDetail {
private PeriodInfo periodInfo;
private EmployerInfo employerInfo;
List<EmployeeInfo> employeeInfo;
List<Messages> messages;
public PeriodInfo getPeriodInfo() {
return periodInfo;
}
public void setPeriodInfo(PeriodInfo periodInfo) {
this.periodInfo = periodInfo;
}
public EmployerInfo getEmployerInfo() {
return employerInfo;
}
public void setEmployerInfo(EmployerInfo employerInfo) {
this.employerInfo = employerInfo;
}
public List<EmployeeInfo> getEmployeeInfo() {
return employeeInfo;
}
public void setEmployeeInfo(List<EmployeeInfo> employeeInfo) {
this.employeeInfo = employeeInfo;
}
public List<Messages> getMessages() {
return messages;
}
public void setMessages(List<Messages> messages) {
this.messages = messages;
}
}
I made the following changes and the code worked for me.
Main Class:
InputStream inputStream = resource.getInputStream();
ObjectMapper objectMapper = new ObjectMapper();
MasMonthlyReportDetailHolder masMonthlyReportDetailHolder = objectMapper.readValue(inputStream, MasMonthlyReportDetailHolder.class);
List<MasMonthlyReportDetail> masMonthlyReportDetail = masMonthlyReportDetailHolder.getMasMonthlyReportDetail();
MasMonthlyReportDetailHolder class:
public class MasMonthlyReportDetailHolder {
private List<MasMonthlyReportDetail> masMonthlyReportDetail;
#JsonProperty("Filing")
public List<MasMonthlyReportDetail> getMasMonthlyReportDetail() {
return masMonthlyReportDetail;
}
public void setMasMonthlyReportDetail(
List<MasMonthlyReportDetail> masMonthlyReportDetail) {
this.masMonthlyReportDetail = masMonthlyReportDetail;
}
}
Adding #JsonProperty("Filing") is the key to avoid this issue. In case of any other procedure, do let me know.
have u tried this ?
jacksonObjectMapper.reader(MasMonthlyReportDetail.class).withRootName("Filing").readValue(jsonAsString);