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]]]]
Related
Solve it by replacing all Date types to String
It's a JSON from marvel comics API I'm trying to deserialize and I'm getting
"com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance
of `com.example.demo.json2csharp.Date` (although at least one Creator exists):
no String-argument constructor/factory method to deserialize from String value
('2019-11-07T08:46:15-0500')"
, example of JSON:
{
"code": 200,
"status": "Ok",
"copyright": "© 2021 MARVEL",
"attributionText": "Data provided by Marvel. © 2021 MARVEL",
"attributionHTML": "Data provided by Marvel. © 2021 MARVEL",
"etag": "f712574873e89d0505dc68a908170fb7970d2f13",
"data": {
"offset": 0,
"limit": 20,
"total": 1,
"count": 1,
"results": [
{
"id": 82967,
"digitalId": 0,
"title": "Marvel Previews (2017)",
"issueNumber": 0,
"variantDescription": "",
"description": null,
"modified": "2019-11-07T08:46:15-0500",
"isbn": "",
"upc": "75960608839302811",
"diamondCode": "",
"ean": "",
"issn": "",
"format": "",
"pageCount": 112,
"textObjects": [
],
"resourceURI": "http://gateway.marvel.com/v1/public/comics/82967",
"urls": [
{
"type": "detail",
"url": "http://marvel.com/comics/issue/82967/marvel_previews_2017?utm_campaign=apiRef&utm_source=9a0517af422c1dfbe132dbaf086fa7f7"
}
],
"series": {
"resourceURI": "http://gateway.marvel.com/v1/public/series/23665",
"name": "Marvel Previews (2017 - Present)"
},
"variants": [
{
"resourceURI": "http://gateway.marvel.com/v1/public/comics/82965",
"name": "Marvel Previews (2017)"
},
{
"resourceURI": "http://gateway.marvel.com/v1/public/comics/82970",
"name": "Marvel Previews (2017)"
}
],
"collections": [
],
"collectedIssues": [
],
"dates": [
{
"type": "onsaleDate",
"date": "2099-10-30T00:00:00-0500"
},
{
"type": "focDate",
"date": "2019-10-07T00:00:00-0400"
}
],
"prices": [
{
"type": "printPrice",
"price": 0
}
],
"thumbnail": {
"path": "http://i.annihil.us/u/prod/marvel/i/mg/b/40/image_not_available",
"extension": "jpg"
},
"images": [
],
"creators": {
"available": 1,
"collectionURI": "http://gateway.marvel.com/v1/public/comics/82967/creators",
"items": [
{
"resourceURI": "http://gateway.marvel.com/v1/public/creators/10021",
"name": "Jim Nausedas",
"role": "editor"
}
],
"returned": 1
},
"characters": {
"available": 0,
"collectionURI": "http://gateway.marvel.com/v1/public/comics/82967/characters",
"items": [
],
"returned": 0
},
"stories": {
"available": 2,
"collectionURI": "http://gateway.marvel.com/v1/public/comics/82967/stories",
"items": [
{
"resourceURI": "http://gateway.marvel.com/v1/public/stories/183698",
"name": "cover from Marvel Previews (2017)",
"type": "cover"
},
{
"resourceURI": "http://gateway.marvel.com/v1/public/stories/183699",
"name": "story from Marvel Previews (2017)",
"type": "interiorStory"
}
],
"returned": 2
},
"events": {
"available": 0,
"collectionURI": "http://gateway.marvel.com/v1/public/comics/82967/events",
"items": [
],
"returned": 0
}
}
]
}
}
My Date class, like all the others class used in ObjectMapper, was generated at https://json2csharp.com/json-to-pojo:
public class Date {
#JsonProperty("type")
public String getType() {
return this.type;
}
public void setType(String type) {
this.type = type;
}
String type;
#JsonProperty("date")
public Date getDate() {
return this.date;
}
public void setDate(Date date) {
this.date = date;
}
Date date;
public Date() {
}
}
The method calling the mapper is this:
#PostMapping
public Root getComic(#RequestBody ComicPostRequestBody comicPostRequestBody) throws NoSuchAlgorithmException, URISyntaxException, IOException {
URI uri = comicService.makeUrl(comicPostRequestBody.getComicId());
String json = client.getComic(uri);
ObjectMapper mapper = new ObjectMapper();
Root comicWrapper = mapper.readValue(json, Root.class);
return comicWrapper;
}
Root is the Class that contains all properties
public class Root {
int code;
String status;
String copyright;
String attributionText;
String attributionHTML;
String etag;
Data data;
#JsonProperty("code")
public int getCode() {
return this.code;
}
public void setCode(int code) {
this.code = code;
}
#JsonProperty("status")
public String getStatus() {
return this.status;
}
public void setStatus(String status) {
this.status = status;
}
#JsonProperty("copyright")
public String getCopyright() {
return this.copyright;
}
public void setCopyright(String copyright) {
this.copyright = copyright;
}
#JsonProperty("attributionText")
public String getAttributionText() {
return this.attributionText;
}
public void setAttributionText(String attributionText) {
this.attributionText = attributionText;
}
#JsonProperty("attributionHTML")
public String getAttributionHTML() {
return this.attributionHTML;
}
public void setAttributionHTML(String attributionHTML) {
this.attributionHTML = attributionHTML;
}
#JsonProperty("etag")
public String getEtag() {
return this.etag;
}
public void setEtag(String etag) {
this.etag = etag;
}
#JsonProperty("data")
public Data getData() {
return this.data;
}
public void setData(Data data) {
this.data = data;
}
public Root() {
}
}
My final goal is to create a comic with:
results.id
results.title
results.description
results.isbn
results.price
I'm new to programming at all and the way I found to do it was to deserialize all the json into a Root, so I can get all these properties like root.getData().getResults()
If there's a simple way to solve this or to deserialize this JSON I'll be glad to know
Thanks
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
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.
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
}
I am trying to parse following response using gson library:
{
"successful": true,
"resultObject": {
"areas": {
"New york": [{
"id": 1,
"name": "Some area 1 in NY"
}, {
"id": 2,
"name": "Some area 2 in NY"
}, {
"id": 3,
"name": "Some area 3 in NY"
}],
"San Fransisco": [{
"id": 1,
"name": "Some area 1 in SF"
}, {
"id": 2,
"name": "Some area 2 in SF"
}, {
"id": 3,
"name": "Some area 3 in SF"
}],
"New Jersey": [{
"id": 1,
"name": "Some area 1 in NJ"
}, {
"id": 2,
"name": "Some area 2 in NJ"
}, {
"id": 3,
"name": "Some area 3 in NJ"
}]
}
}
}
I was trying to use
Pair<String, City[]>[] cities;
to parse the areas key but it is coming as null every time. Java code for City class:
public class City {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "ClassPojo [id = " + id + ", name = " + name + "]";
}
}
Any help is appreciated.
If the whole json needs to be parsed, I suggest you use a custom class, like this one:
public class GsonContainer{
public boolean successful;
public ResultObject resultObject;
public static class ResultObject{
public Map<String, List<City>> areas;
}
}//end class
If it is only the json under areas, use a Map<String,List<City>> instead.