Combine 2 MongoDB collections in Java - java

I have 2 MongoDB collections, named "product" and "file_data", "file_data" contains images of a single product in "product" by productId.
Entity Product
public class Product {
private String id;
private String link;
private String externalId;
private String createdBy;
private Date createdStamp;
}
Entity FileData
public class FileData {
private String id;
private Date date;
private String createdBy;
private String productId;
private String fileName;
How can I retrieve product information as JSON like this:
"data": {
"id": "3793",
"link": "https://example.com/abc.jpg,
"externalId": "562282907969",
"createdBy": "123456#gmail.com",
"createdStamp": 1624330935051,
"images": {
"id": "zxc",
"date": "1624330935051",
"createdBy": "123456#gmail.com",
"productId": "3793",
"fileName": "abc.jpg",
},
{
"id": "zxc",
"date": "1624330935051",
"createdBy": "123456#gmail.com",
"productId": "3793",
"fileName": "abc.jpg",
},
}
Here is my code:
#GET
#Produces(MediaType.APPLICATION_JSON)
public Response getProducts() {
try {
HashMap<String, Object> result = new HashMap<>();
JSONArray list = new JSONArray();
List<Product> products = getProductManager().getProductsByPartyId(getAuth().getString("partyGroupId"));
if (null != products && products.size() > 0) {
products.forEach(product -> {
list.put(getFileDataManager().getFileDataList(product.getId(), "PRODUCT"));
});
result.put("data", products);
result.put("status", 1);
}
return result(result);
} catch (Exception ex) {
ex.printStackTrace();
return Response.status(400).entity(getErrorMessage(ex.getMessage())).build();
}
}
It only shows
"data": {
"id": "3793",
"link": "https://example.com/abc.jpg,
"externalId": "562282907969",
"createdBy": "123456#gmail.com",
"createdStamp": 1624330935051,
}
Please help me. Thank you

Related

How can I convert a JSON string of objects into an ArrayList using Gson?

So I have a JSON string of countries like this:
{
"details": [
{
"country_id": "1",
"name": "Afghanistan",
"regions": null
},
{
"country_id": "2",
"name": "Albania",
"regions": null
},
{
"country_id": "3",
"name": "Algeria",
"regions": null
},
... and so on
}
Now I want to have a method that tries to convert this into an ArrayList of countries.
public static ArrayList<GFSCountry> get() {
return new Gson().fromJson(countriesJson, new TypeToken<ArrayList<GFSCountry>>(){}.getType());
}
But I get an
Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path
As per request, here is my GFSCountry class:
#SerializedName("country_id")
#Expose
private String countryId;
#SerializedName("name")
#Expose
private String name;
#SerializedName("regions")
#Expose
private Object regions;
public String getCountryId() {
return countryId;
}
public void setCountryId(String countryId) {
this.countryId = countryId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Object getRegions() {
return regions;
}
public void setRegions(Object regions) {
this.regions = regions;
}
I know I should adjust something either from the JSON string or the method. Any help?
Since the list is nested in your JSON you will need a small mapping class that contains the list.
Try
static class GFSCountryList {
public List<GFSCountry> details;
}
public static List<GFSCountry> get() {
return new Gson().fromJson(countriesJson, GFSCountryList.class).details;
}
It seems to me that Gson is expecting your json to be like this
[
{
"country_id": "1",
"name": "Afghanistan",
"regions": null
},
{
"country_id": "2",
"name": "Albania",
"regions": null
},
{
"country_id": "3",
"name": "Algeria",
"regions": null
},
... and so on
]
But it encounters an object (marked by { })
Either you have the possibility to change your json format, or you create a class with a "details" attribut as a list to be compatible with the json's format.

how to return customized json as output in Springboot JPA?

I have two entities responsible for fetching data from two different tables and i have created a class to display the combined result of those two entities. I am able to fetch the data using JPA but the output is not in the desired JSON format.
First Entity,
#Entity
#Table(name="basicinfo")
public class Rfx_BasicInfo implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(unique = true)
private String uniqueid;
private String description;
private String uniqueidstatus;
private LocalDateTime startdate;
private LocalDateTime enddate;
private String createdby;
public String getCreatedby() {
return createdby;
}
public Long getId() {
return id;
}
public String getUniqueid() {
return uniqueid;
}
public String getDescription() {
return description;
}
public LocalDateTime getStartdate() {
return startdate;
}
public LocalDateTime getEnddate() {
return enddate;
}
public String getUniqueidstatus() {
return uniqueidstatus;
}
}
and the Second one,
#Entity
#Table(name="supplierinvite")
public class Rfx_SupplierInvite {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String externalstatus;
private String uniqueid;
public String getExternalstatus() {
return externalstatus;
}
public String getUniqueid() {
return uniqueid;
}
}
These two are the repositories for the entities i created.
#Repository("rfxBasicInfoRepository")
public interface Rfx_BasicInfoRepository extends JpaRepository<Rfx_BasicInfo,Long> {
#Query(value="SELECT u from Rfx_BasicInfo u where u.createdby = :createdby")
List<Rfx_BasicInfo> findReportByLoginId(#Param("createdby") String createdby);
}
#Repository("rfxSupplierInviteRepository")
public interface Rfx_SupplierInviteRepository extends JpaRepository<Rfx_SupplierInvite,Long> {
#Query(value="SELECT u.uniqueid, u.externalstatus, count(u.externalstatus) from Rfx_SupplierInvite u where u.uniqueid in (:uniqueid) group by u.uniqueid,u.externalstatus order by u.uniqueid, u.externalstatus")
List<Rfx_SupplierInvite> findReportByUniqueId(#Param("uniqueid") String uniqueid);
}
In the first repository i'm fetching the data based on the "createdby" field and in the second one i'm fetching the data based on "uniqueid" field. This "uniqueid" field is common between the two tables. As of now, i have tried to fetch the results separately and merge them into one using a class. I didn't use any JPA mapping and Joins because i'm not sure how to use it here properly.
public class Rfx_Model {
private List<Rfx_BasicInfo> rfx_basicInfoList;
private List<Rfx_SupplierInvite> rfx_supplierInviteList;
public Rfx_Model(List<Rfx_BasicInfo> rfx_basicInfoList, List<Rfx_SupplierInvite> rfx_supplierInviteList) {
this.rfx_basicInfoList = rfx_basicInfoList;
this.rfx_supplierInviteList = rfx_supplierInviteList;
}
public List<Rfx_BasicInfo> getRfx_basicInfoList() {
return rfx_basicInfoList;
}
public List<Rfx_SupplierInvite> getRfx_supplierInviteList() {
return rfx_supplierInviteList;
}
}
This is my controller,
#RequestMapping(value="/buyerLandingReport/{LoginID}",method = RequestMethod.GET)
public ResponseEntity<Object> buyerLandingReport(#PathVariable("LoginID") String LoginID) {
try{
List<Rfx_BasicInfo> list1 = rfxBasicInfoRepository.findReportByLoginId(LoginID);
List<Rfx_SupplierInvite> list2 = rfxSupplierInviteRepository.findReportByUniqueId(list1.get(0).getUniqueid());
return new ResponseEntity(new Rfx_Model(list1,list2),HttpStatus.OK);
}
catch (Exception ex){
throw ex;
}
}
Below is the current JSON ouput,
{
"Rfx_BasicInfo": [
{
"id": 1,
"uniqueid": "RA001",
"description": "sbhdjajd",
"uniqueidstatus": "ajsd",
"startdate": "2018-05-04T12:00:00",
"enddate": "2018-05-04T12:00:00",
"createdby": "RIL01"
},
{
"id": 2,
"uniqueid": "RA001",
"description": "kasksj",
"uniqueidstatus": "sjkds",
"startdate": "2018-05-04T12:00:00",
"enddate": "2018-05-04T12:00:00",
"createdby": "RIL01"
},
{
"id": 3,
"uniqueid": "RA002",
"description": "asjhkdj",
"uniqueidstatus": "asjhd",
"startdate": "2018-05-04T12:00:00",
"enddate": "2018-05-04T12:00:00",
"createdby": "RIL01"
}
],
"Rfx_SupplierInvite": [
[
"uniqueid": "RA001",
"externalstatus":"AC",
"count": 1
],
[
"uniqueid": "RA001",
"externalstatus": "IN",
"count": 2
]
]
}
and the desired JSON ouput format is this one,
[
{
"Rfx_BasicInfo": {
"id": 1,
"uniqueid": "RA001",
"description": "Auction for taking bid for work on route Tirora Gondiya",
"uniqueidstatus": "PB",
"startdate": "2018-05-04T12:00:00",
"enddate": "2018-05-04T14:00:00",
"createdby": "RIL03"
},
"Rfx_Supplier" : [
{
"uniqueid": "RA001",
"externalstatus": "AC",
"count": 1
},
{
"uniqueid": "RA001",
"externalstatus": "IN",
"count": 2
}
]
},
{
"Rfx_BasicInfo": {
"id": 2,
"uniqueid": "RA002",
"description": "Auction for taking bid for work on route Gondiya  -  Amgaon",
"uniqueidstatus": "DR",
"startdate": "2018-05-04T14:00:00",
"enddate": "2018-05-04T16:00:00",
"createdby": "RIL03"
},
"Rfx_Supplier" : [
{
"uniqueid": "RA002",
"ExternalStatus": "AC",
"count": 1
},
{
"uniqueid": "RA002",
"ExternalStatus": "IN",
"count": 2
}
]
}
]
I'd really appreciate any suggestions to help me figure out the solution for this.
You really need the ResponseEntity ? If not, the common way is:
#RestController
public class MyController {
#RequestMapping(value="/buyerLandingReport/{LoginID}")
public Rfx_Model buyerLandingReport(#PathVariable("LoginID") String LoginID) {
try{
List<Rfx_BasicInfo> list1 = rfxBasicInfoRepository.findReportByLoginId(LoginID);
List<Rfx_SupplierInvite> list2 = rfxSupplierInviteRepository.findReportByUniqueId(list1.get(0).getUniqueid());
return new Rfx_Model(list1,list2);
}
catch (Exception ex){
throw ex;
}
}
Change your Controller as
#RequestMapping(value="/buyerLandingReport/{LoginID}",method = RequestMethod.GET)
public ResponseEntity<Object> buyerLandingReport(#PathVariable("LoginID") String LoginID) {
try{
List<Rfx_BasicInfo> list1 = rfxBasicInfoRepository.findReportByLoginId(LoginID);
List<Rfx_SupplierInvite> list2 = rfxSupplierInviteRepository.findReportByUniqueId(list1.get(0).getUniqueid());
List<Rfx_Model> body = Arrays.asList(new Rfx_Model(list1, list2);
return new ResponseEntity(body), HttpStatus.OK);
}
catch (Exception ex){
throw ex;
}
}
You need to return a list (or array) to get a json array response.

Json array from JSON response is always null

I am working on rest client program in which I am parsing a json response using gson. My json response is as below
{
"Status": "success",
"Data": [
{
"ID": "123",
"Type": 0,
"OperatorID": null,
"DepartmentID": "128",
"LanguageCode": "en-US",
"WebsiteDefID": "160",
"VisitID": "737",
},
{
"ID": "737867804181437078",
"Type": 0,
"OperatorID": "1785",
"DepartmentID": "200",
"LanguageCode": "en-US",
"WebsiteDefID": "160",
"VisitID": "737",
"CustomFields": {
"Model": "ABCD",
"Question": "ABCD"
}
}
]
}
Gson:
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson= gsonBuilder.create();
Info info = gson.fromJson(inactiveChatMessages, Info.class);
And my Info and Data Pojo class is as below:
public class Info {
private String Status;
private Data[] Data;
public String getStatus() {
return Status;
}
public void setStatus(String status) {
Status = status;
}
public Data[] getData() {
return Data;
}
public void setData(Data[] data) {
Data = data;
}
#Override
public String toString() {
return "ChatInfo [Status=" + Status + ", Data=" + Arrays.toString(Data) + "]";
}
}
Data:
public class Data {
private String ID;
private String OperatorID;
private String DepartmentID;
private CustomFields CustomFields;
public String getID() {
return ChatID;
}
public void setID(String ID) {
ChatID = chatID;
}
public String getOperatorID() {
return OperatorID;
}
public void setOperatorID(String operatorID) {
OperatorID = operatorID;
}
public String getDepartmentID() {
return DepartmentID;
}
public void setDepartmentID(String departmentID) {
DepartmentID = departmentID;
}
#Override
public String toString() {
return "Data [ID=" + ID + ", OperatorID=" + OperatorID + ", DepartmentID=" + DepartmentID + ", CustomFields=" + CustomFields
+ "]";
}
}
In Data pojo from array I am only accessing the fields which I need. But in response I am always getting data array as null. There is no error. So I am really not getting exactly what is going wrong. Can anyone please help me with this?
Info [Status=success, Data=[]]
Your Json is not valid
Your valid json.
{
"Status": "success",
"Data": [{
"ID": "123",
"Type": 0,
"OperatorID": null,
"DepartmentID": "128",
"LanguageCode": "en-US",
"WebsiteDefID": "160",
"VisitID": "737"
},
{
"ID": "737867804181437078",
"Type": 0,
"OperatorID": "1785",
"DepartmentID": "200",
"LanguageCode": "en-US",
"WebsiteDefID": "160",
"VisitID": "737",
"CustomFields": {
"Model": "ABCD",
"Question": "ABCD"
}
}
]
}
for json validation you can use https://jsonlint.com/
otherwise your code is working fine.
here is output
ChatInfo [Status=success, Data=[Data [ID=123, OperatorID=null, DepartmentID=128, CustomFields=null], Data [ID=737867804181437078, OperatorID=1785, DepartmentID=200, CustomFields=[Model=ABCD,question=ABCD]]]]

Expected BEGIN_OBJECT but was BEGIN_ARRAY for JSON parsing using GSON

Expected BEGIN_OBJECT but was BEGIN_ARRAY for JSON parsing using GSON.
I'm getting error which is occur due to class define for Gson Json implementation
Json Format which need to parse using GSON
{
"StatusCode": 4,
"Data": {
"Data": [
[
{"Value": "19"},{"Value": "19"}],
[
{"Value": "77"},{"Value": "4"}
]
],
"ColumnHeaders": [
{
"Width": "11.0%",
"Title": "Date"
},
{
"Width": "7.6%",
"Title": "Total Clicks"
}
],
"ColumnHeaderGroups": [
{
"ColSpan": "1",
"Title": ""
},
{
"ColSpan": "7",
"Title": "Chats"
},
{
"ColSpan": "3",
"Title": "Times (HH:MM:SS)"
}
],
"ReportHeaders": [
{
"Name": "Title",
"Value": "Chat Summary By Date"
},
{
"Name": "Run Date",
"Value": "05/03/2016 10:52:39 AM"
},
{
"Name": "Time Zone",
"Value": "GMT+00:00"
}
],
"Summary": [
{
"Value": "96"
},
{
"Value": "23"
}
]
},
"Status": "success"
}
Classes for parsing using gson :
static class Page {
String Status;
Data Data;
}
static class Data {
String ReportID;
}
static class Page1 {
String StatusCode;
String Status;
Data1 Data;
}
static class Data1 {
List <Data2> Data;
List<ColumnHeaders> ColumnHeaders;
List<ReportHeaders> ReportHeaders;
List<Summary> Summary;
}
static class Data2{
List<object1> object1;
}
static class object1 {
String Value;
}
static class ColumnHeaders {
String Title;
}
static class Summary {
String Value;
}
static class ReportHeaders {
String Value;
}
Code for parsing json using gson:
need to parse
"Value": "19","Value": "19","Value": "77","Value": "4"
inside Data Array[].
Gson gson = new Gson();
Page1 page = gson.fromJson(json, Page1.class);
String statusString = page.Status;
System.out.println("Status : " + statusString);
System.out.println("StatusCode : " + page.StatusCode);
if ("success".equals(statusString)) {
System.out.println("Inside if");
for (ColumnHeaders item : page.Data.ColumnHeaders)
System.out.print(item.Title + " :");
System.out.println();
for (Summary item1 : page.Data.Summary)
System.out.print(item1.Value + " :");
}
Try changing pojo to this
class Data{
#SerializedName("Data")
#Expose
private List<List<Data2>> Data = new ArrayList<List<Data2>>();
#SerializedName("ColumnHeaders")
#Expose
private List<ColumnHeader> ColumnHeaders = new ArrayList<ColumnHeader>();
#SerializedName("ReportHeaders")
#Expose
private List<ReportHeader> ReportHeaders = new ArrayList<ReportHeader>();
#SerializedName("Summary")
#Expose
private List<Summary> Summary = new ArrayList<Summary>();
//getter setter
}
class Data2{
#SerializedName("Value")
#Expose
private String Value;
//getter setter
}

How to deserialize json with a string-url name-value pair

I have json response in the form
{
"total": 782,
"category": {
"id": 1120,
"name": "Computers & Programming"
},
"experts": [
{
"id": 385816,
"name": "Master Z",
"title": "Mr",
"description": " Expert in C++",
"profile": "http://...com/experts.svc/1.0/385816/..../json?.."
}
}
]
}
I am able to parse everything else in the experts[] array except "profile" whose value "http://...com/experts.svc/1.0/385816/..../json?.." has the following json response
{
"id": 385816,
"name": "Master Z",
"title": "",
"reviewsCount": 15359,
"averageRating": 4.87,
"status": 4,
"fee": 19.99,
"languages": "English",
"category": {
"id": 1120,
"name": "Computers & Programming"
}
}
The models used are as follows
1. main pojo:
public class ExpertObj
{
private String total;
private Category category;
private Experts[] experts;
}
Category pojo:
public class Category
{
private String id;
private String name;
}
3.Experts array pojo:
public class Experts
{
private String id;
private String name;
private String title;
private String description;
private String profile;
}
Am using Retrift 2.
private RestManager mManager;
List<Expert> mExperts = new ArrayList<>();
....
Call<ExpertsObj> call = mManager.getExpertsService().listAllExperts();
call.enqueue(new Callback<ExpertsObj>() {
#Override
public void onResponse(Call<ExpertsObj> call, Response<ExpertsObj> response) {
if (response.isSuccess()) {
ExpertsObj expertsObj = response.body();
mExperts = expertsObj.getExperts();
....}
At a loss how to parse the profile-url name-value pair and display the results in a detail layout in android.
Any help is appreciated.
New in android. Please excuse if anything is not explained properly.

Categories