Embedding a json array within json object - java

Im using the following code to put up a json array within json object;
import org.json.JSONObject;
public class PollingPoJo {
int id;
String topic;
String description;
String pollItem1;
String pollItem2;
String pollItem3;
String pollItem4;
ArrayList<String> pollingItem ;
public PollingPoJo(int id, String topic, String description, String pollItem1, String pollItem2, String pollItem3,
String pollItem4) {
super();
this.id = id;
this.topic = topic;
this.description = description;
this.pollItem1 = pollItem1;
this.pollItem2 = pollItem2;
this.pollItem3 = pollItem3;
this.pollItem4 = pollItem4;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPollItem1() {
return pollItem1;
}
public void setPollItem1(String pollItem1) {
this.pollItem1 = pollItem1;
}
public String getPollItem2() {
return pollItem2;
}
public void setPollItem2(String pollItem2) {
this.pollItem2 = pollItem2;
}
public String getPollItem3() {
return pollItem3;
}
public void setPollItem3(String pollItem3) {
this.pollItem3 = pollItem3;
}
public String getPollItem4() {
return pollItem4;
}
public void setPollItem4(String pollItem4) {
this.pollItem4 = pollItem4;
}
#Override
public String toString() {
pollingItem = new ArrayList<>();
pollingItem.add(pollItem1);
pollingItem.add(pollItem2);
pollingItem.add(pollItem3);
pollingItem.add(pollItem4);
String jObj = new JSONObject().put("id",id)
.put("topic", topic)
.put("description", description)
.put("pollingItems", pollItem1).toString();
return jObj;
}
}
Later on Im using the following code to generate the response.
#POST
#Path("polling")
#Produces(MediaType.APPLICATION_JSON)
public static String getCurrentPoll() {
ArrayList<PollingPoJo> output = new ArrayList<PollingPoJo>();
try {
Connection connection = MyResource.getConnection();
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM POLLING order by id desc limit 1 ");
output = new ArrayList<PollingPoJo>();
while (rs.next()) {
PollingPoJo trending = new PollingPoJo(rs.getInt("ID"), rs.getString("TOPIC"), rs.getString("DESCRIPTION"),
rs.getString("ITEM1"), rs.getString("ITEM2"), rs.getString("ITEM3"),
rs.getString("ITEM4"));
output.add(trending);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return output.toString();
}
But the resulting json response does not contain json within it. Though I have embedded a array list within toString , it is not showing up. How can I be able to sort this out?
Following is the expected sample response,
{ "topic": "Fruits", "description":
"My favourite fruits", "id": 1,
"polling_items": [
"Item 1",
"Item 2",
"Item 3" ] }
but it is throwing the following response,
[ {
"topic": "Fruits",
"description": "My favourite fruits",
"id": 1,
"pollingItems": "item1" } ]
As you could see, pollingitems contains no json array. How can I be able to sort this out?

In your PollingPoJo, you should have a collection with name polling_items. And in the constructor of PollingPoJo, add the 3,4,5,6 parameters to this collection.

Related

Error com.fasterxml.jackson.core.JsonParseException: Unrecognized token

Trying to read a JSON file and serialize it to java object, I wrote a method:
public static PostPojo readFile(String titleFile){
String pathJSONFile = "src/main/resources/"+titleFile+".json";
ObjectMapper objectMapper = new ObjectMapper();
try {
objectMapper.readValue(pathJSONFile,PostPojo.class);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return postPojo;
}
but it produces an error:
com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'src': was expecting (JSON
String, Number, Array, Object or token 'null', 'true' or 'false')
at [Source: (String)"src/main/resources/ninetyNinthPost.json"; line: 1, column: 4]
at utils.ApiUtils.readFile(ApiUtils.java:71)
at ApiApplicationRequest.getValue(ApiApplicationRequest.java:31)
My JSON file from which values are calculated
[ {
"userId" : 10,
"id" : 99,
"title" : "temporibus sit alias delectus eligendi possimus magni",
"body" : "quo deleniti praesentium dicta non quod\naut est
molestias\nmolestias et officia quis nihil\nitaque dolorem quia"
} ]
My java object class
public class PostPojo {
private int userId;
private int id;
private String title;
private String body;
public PostPojo() {
}
public PostPojo(int userId, int id, String title, String body) {
this.userId = userId;
this.id = id;
this.title = title;
this.body = body;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
#Override
public String toString() {
return "PostModel{" +
"userId=" + userId +
", id=" + id +
", title='" + title + '\'' +
", body='" + body + '\'' +
'}';
}
}
I really don't understand what is the reason.As I understand it, reading in the documentation, it should read the file and present it in the java class. Any sugestions?
There is no method signature supposed to get a file path as first argument. You may pass a JSON String as first argument or you could use the method signature with a File Object as first argument, like this:
public static PostPojo[] readFile(String titleFile){
String pathJSONFile = "src/main/resources/"+titleFile+".json";
ObjectMapper objectMapper = new ObjectMapper();
File jsonFile = new File(pathJSONFile);
PostPojo[] postPojo = null;
try {
postPojo = objectMapper.readValue(jsonFile, PostPojo[].class);
} catch (IOException e) {
e.printStackTrace();
}
return postPojo;
}
EDIT: Since your file defines a wrapping array around the object you have to parse it as array. Afterwards you may return it as an array like i did in my edited answer or you just return the first array record.

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $

Ok, So I read a couple other questions with this same error, but none have been answered as working, and doesnt seem like I can get it working.
I am connecting to google in-app billing and have everything set up, but, when I try to pull my skudetails (I have 2 SKUs there now), I get the error -
Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
I have a SubscriptionActivity, Result (serializable), and Details model class (serializable). Below is the code, any help will be great, thanks-
From subscriptionactivity:
Gson gson = new Gson();
try {
Result result = gson.fromJson(skuDetailsList.toString(), Result.class);
if (result != null) {
for (Details d : result.getDetails()) {
System.out.println(d.getProductId()
+ " \n " + d.getTitle() + " \n " + d.getDescription() + " \n "
+ d.getPrice());
}
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
From details model:
public class Details implements Serializable{
#SerializedName("productId")
#Expose
private String productId;
#SerializedName("type")
#Expose
private String type;
#SerializedName("price")
#Expose
private String price;
#SerializedName("price_amount_micros")
#Expose
private Integer priceAmountMicros;
#SerializedName("price_currency_code")
#Expose
private String priceCurrencyCode;
#SerializedName("subscriptionPeriod")
#Expose
private String subscriptionPeriod;
#SerializedName("freeTrialPeriod")
#Expose
private String freeTrialPeriod;
#SerializedName("title")
#Expose
private String title;
#SerializedName("description")
#Expose
private String description;
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public Integer getPriceAmountMicros() {
return priceAmountMicros;
}
public void setPriceAmountMicros(Integer priceAmountMicros) {
this.priceAmountMicros = priceAmountMicros;
}
public String getPriceCurrencyCode() {
return priceCurrencyCode;
}
public void setPriceCurrencyCode(String priceCurrencyCode) {
this.priceCurrencyCode = priceCurrencyCode;
}
public String getSubscriptionPeriod() {
return subscriptionPeriod;
}
public void setSubscriptionPeriod(String subscriptionPeriod) {
this.subscriptionPeriod = subscriptionPeriod;
}
public String getFreeTrialPeriod() {
return freeTrialPeriod;
}
public void setFreeTrialPeriod(String freeTrialPeriod) {
this.freeTrialPeriod = freeTrialPeriod;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
From Result activity:
public class Result implements Serializable{
#SerializedName("SkuDetails")
#Expose
private ArrayList<Details> details = new ArrayList<Details>();
/**
*
* #return The SkuDetails
*/
public ArrayList<Details> getDetails() {
return details;
}
/**
*
* #param details
* The details
*/
public void setDetails(ArrayList<Details> details) {
this.details = details;
}
}*
Oh..and the response I was trying to parse (skuDetailsList.toString()) is:
[
SkuDetails: {
"productId": "basic_sub",
"type": "subs",
"price": "$0.99",
"price_amount_micros": 990000,
"price_currency_code": "USD",
"subscriptionPeriod": "P1M",
"freeTrialPeriod": "P4W2D",
"title": "Basic Subscription Service (DadBod Recipes)",
"description": "Basic Subscription Service for DadBodRecipes"
},
SkuDetails: {
"productId": "enterprise_sub",
"type": "subs",
"price": "$2.99",
"price_amount_micros": 2990000,
"price_currency_code": "USD",
"subscriptionPeriod": "P1M",
"freeTrialPeriod": "P4W2D",
"title": "Enterprise Subscription Service (DadBod Recipes)",
"description": "Enterprise Subscription Service for DadBodRecipes"
}
]
Issue is because, the result you're getting is as <Key-Value> pair (not as JSON object/Array, but similar to it).
So you'll need to make it to JSONObject first and then parse it using Gson like below:
Map<String, String> params = skuDetailsList;
JSONObject object = new JSONObject(params);
Result result = gson.fromJson(object.toString(), Result.class);
Do like this, hope it helps !
You are trying to parse your json
[
as
{
when you see the [ it represents a list
when you see the { it represents an object.
I'm pretty sure you know that as you built a wrapper class, but your wrapper class is also an object, not an array.
So your choices are to have your wrapper class extend ArrayList or some form of List.
Or
Tell your Json converter that the base is an Array and you want the first object in the list is an object of your type.

Parsing array of object using Gson

My Rest service produces response as below
{
"feeds": [
{
"id": 672,
"imagePath": "http://pixyfi.com/uploads/image1.jpg",
"description": "Off White Cotton Net^The Dress Is Made From Cotton Net. It Is Stretchable And The Material Is Really Good. It Is A Bodycon Dress.",
"uploader": {
"id": 459,
},
"rejected": false,
"moderator": {
"id": 95,
},
"moderatedOn": "2016-12-19"
"imagePaths": [
"uploads/image1.jpg"
]
},
{
"id": 672,
"imagePath": "http://pixyfi.com/uploads/mage2.jpg",
"description": "Off White Cotton Net^The Dress Is Made From Cotton Net. It Is Stretchable And The Material Is Really Good. It Is A Bodycon Dress.",
"uploader": {
"id": 459,
},
"rejected": false,
"moderator": {
"id": 95,
},
"moderatedOn": "2016-12-19"
"imagePaths": [
"uploads/image2.jpg"
]
}
]
}
How can i parse it with Gson. IN my android client also i have same Feed Class witch which this JSON was generated.
Note: I have used Spring boot for my rest API and this JSON was generated with ResponseEntity.
Firstly, make sure that you have got valid JSON. The above in your case is not valid.
If a json object contains a single element, then there is no need to place comma after that. (comma after id in moderator and uploader object). You need to remove that.Also you need to place a comma after moderatedOn value.
Now after you got valid one, you have a feed class. In order to map your json feeds Array onto your List. You need to do the following.
Gson gson = new Gson();
Type feedsType = new TypeToken<ArrayList<Feed>>(){}.getType();
List<Feed> feedList = gson.fromJson(yourJsonResponseArray, feedsType);
Your Classes are must be like these.
Feed Class
public class Feed
{
private String id;
private String imagePath;
private Moderator moderator;
private String description;
private String rejected;
private Uploader uploader;
private String moderatedOn;
private String[] imagePaths;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String getImagePath ()
{
return imagePath;
}
public void setImagePath (String imagePath)
{
this.imagePath = imagePath;
}
public Moderator getModerator ()
{
return moderator;
}
public void setModerator (Moderator moderator)
{
this.moderator = moderator;
}
public String getDescription ()
{
return description;
}
public void setDescription (String description)
{
this.description = description;
}
public String getRejected ()
{
return rejected;
}
public void setRejected (String rejected)
{
this.rejected = rejected;
}
public Uploader getUploader ()
{
return uploader;
}
public void setUploader (Uploader uploader)
{
this.uploader = uploader;
}
public String getModeratedOn ()
{
return moderatedOn;
}
public void setModeratedOn (String moderatedOn)
{
this.moderatedOn = moderatedOn;
}
public String[] getImagePaths ()
{
return imagePaths;
}
public void setImagePaths (String[] imagePaths)
{
this.imagePaths = imagePaths;
}
}
Moderator Class
public class Moderator
{
private String id;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
}
Uploader Class
public class Uploader
{
private String id;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
}

Cannot Parse a JSON response that is received by RestTemplate

I need to parse a JSON response that I receive from a web service but I am receiving following error message, I puzzled with the this. I tried it without Results class as well to no avail. Any help would be appreciated.
The request sent by the client was syntactically incorrect.
Code
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new
MappingJackson2HttpMessageConverter());
ResponseEntity<Results> responseEntity = restTemplate
.getForEntity(
"http://primesport.sieenasoftware.com/QryApi
/GetEvents?
username=username&
password=password&
userid=23",
Results.class);
System.err.println(">>" + responseEntity.getBody().getEvents().size());
Classes
Results
public class Results {
private List<Events> events;
getter and setter
}
Events
public class Event {
private long eventId;
private String name;
private String subTitle;
private String description;
private String localDate;
private String localDateFrom;
private String imageUrl;
private int venueId;
private String venue;
private int availableTickets;
private long performerId;
private String performer;
private String performerType;
private int subcategoryId;
private String urlCategoryName;
private String metaTitle;
private String metaDescription;
private String primeSportUrl;
private String sectionWiseView;
private String venueCity;
private String venueState;
private String snippetDate;
private int eiProductionId;
private boolean requireBillingAsShipping;
public long getEventId() {
return eventId;
}
public void setEventId(long eventId) {
this.eventId = eventId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSubTitle() {
return subTitle;
}
public void setSubTitle(String subTitle) {
this.subTitle = subTitle;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getLocalDate() {
return localDate;
}
public void setLocalDate(String localDate) {
this.localDate = localDate;
}
public String getLocalDateFrom() {
return localDateFrom;
}
public void setLocalDateFrom(String localDateFrom) {
this.localDateFrom = localDateFrom;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public int getVenueId() {
return venueId;
}
public void setVenueId(int venueId) {
this.venueId = venueId;
}
public String getVenue() {
return venue;
}
public void setVenue(String venue) {
this.venue = venue;
}
public int getAvailableTickets() {
return availableTickets;
}
public void setAvailableTickets(int availableTickets) {
this.availableTickets = availableTickets;
}
public long getPerformerId() {
return performerId;
}
public void setPerformerId(long performerId) {
this.performerId = performerId;
}
public String getPerformer() {
return performer;
}
public void setPerformer(String performer) {
this.performer = performer;
}
public String getPerformerType() {
return performerType;
}
public void setPerformerType(String performerType) {
this.performerType = performerType;
}
public int getSubcategoryId() {
return subcategoryId;
}
public void setSubcategoryId(int subcategoryId) {
this.subcategoryId = subcategoryId;
}
public String getUrlCategoryName() {
return urlCategoryName;
}
public void setUrlCategoryName(String urlCategoryName) {
this.urlCategoryName = urlCategoryName;
}
public String getMetaTitle() {
return metaTitle;
}
public void setMetaTitle(String metaTitle) {
this.metaTitle = metaTitle;
}
public String getMetaDescription() {
return metaDescription;
}
public void setMetaDescription(String metaDescription) {
this.metaDescription = metaDescription;
}
public String getPrimeSportUrl() {
return primeSportUrl;
}
public void setPrimeSportUrl(String primeSportUrl) {
this.primeSportUrl = primeSportUrl;
}
public String getSectionWiseView() {
return sectionWiseView;
}
public void setSectionWiseView(String sectionWiseView) {
this.sectionWiseView = sectionWiseView;
}
public String getVenueCity() {
return venueCity;
}
public void setVenueCity(String venueCity) {
this.venueCity = venueCity;
}
public String getVenueState() {
return venueState;
}
public void setVenueState(String venueState) {
this.venueState = venueState;
}
public String getSnippetDate() {
return snippetDate;
}
public void setSnippetDate(String snippetDate) {
this.snippetDate = snippetDate;
}
public int getEiProductionId() {
return eiProductionId;
}
public void setEiProductionId(int eiProductionId) {
this.eiProductionId = eiProductionId;
}
public boolean isRequireBillingAsShipping() {
return requireBillingAsShipping;
}
public void setRequireBillingAsShipping(boolean requireBillingAsShipping) {
this.requireBillingAsShipping = requireBillingAsShipping;
}
}
Partial Response
[{
"EventId":1000250537,
"Name":"US Open Golf",
"SubTitle":null,
"Description":"US Open Golf Tickets",
"Date":"\/Date(1434873560000)\/",
"LocalDate":"6/20/2015 11:59 PM",
"LocalDateFrom":null,
"ImageUrl":null,
"VenueId":146566,
"Venue":"Chambers Bay Golf Course",
"AvailableTickets":33,
"PerformerId":151551,
"Performer":"US Open Golf",
"PerformerType":"Golf",
"SubcategoryId":55,
"UrlCategoryName":"Sports",
"MetaTitle":null,
"MetaDescription":null,
"PrimeSportUrl":"http://primesport.sieenasoftware.com/e/sports/us-open-golf/chambers-bay-golf-course/",
"SectionWiseView":null,
"VenueCity":"UNIVERSITY PLACE",
"VenueState":"WA",
"SnippetDate":null,
"EIProductionId":99985,
"RequireBillingAsShipping":false},
{
"EventId":1000253479,
"Name":"Womens College World Series",
"SubTitle":null,
"Description": .....
UPDATE
I know JAXB can be used for both JSON and XML, I am trying to use it to see if it would help to solve the issue.
UPDATE
The code is returning following exception:
org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Can not deserialize instance of com.myproject.myevent.Results out of START_ARRAY token
at [Source: java.io.PushbackInputStream#dedcd10; line: 1, column: 1]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of com.myproject.myevent.Results out of START_ARRAY token
at [Source: java.io.PushbackInputStream#dedcd10; line: 1, column: 1]
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:208)
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:200)
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:97)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:809)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:793)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:576)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:529)
at org.springframework.web.client.RestTemplate.getForEntity(RestTemplate.java:261)
at com.myproject.service.TicketSeviceImpl.primeSport(TicketSeviceImpl.java:217)
at com.myproject.service.TicketSeviceImpl.findTicket(TicketSeviceImpl.java:45)
at com.myproject.web.TicketController.findTicket(TicketController.java:29)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
UPDATE
following code returns
Code
try {
System.err.println(">>> primeSport");
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(
new MappingJackson2HttpMessageConverter());
ResponseEntity<Event[]> responseEntity = restTemplate
.getForEntity(
"http://primesport.sieenasoftware.com/QryApi/GetEvents?username=username&password=password&userid=23",
Event[].class);
System.err.println(">>" + responseEntity.getBody().length);
System.err.println(">>" + responseEntity.getBody()[0].getEventId());
System.err.println(">>" + responseEntity.getBody()[1].getEventId());
} catch (Exception e) {
e.printStackTrace();
}
Output
>1532
>0
>0
Can you try the following and see whether helps:
ResponseEntity<Events[]> responseEntity = restTemplate
.getForEntity(
"http://primesport.sieenasoftware.com/QryApi
/GetEvents?
username=username&
password=password&
userid=23",
Events[].class);
System.err.println(">>" + responseEntity.getBody().length);
For mapping the fields to the JSON members you can use Jackson annotation JSONProperty("EventId") can be used for the eventId field. Similarly for others.
#JsonProperty("EventId")
private long eventId;
#JsonProperty("Name")
private String name;
Have you tried to see the exact request getting generated? Let's say in a proxy software like fiddler/charles?
Sometimes I have experienced, the framework adds additional constructs(encoding, etc), before the requests actually really gets to the wire(or reaching the server endpoint).
Try this, to create the request. Even the documentation for RestTemplate suggests to avoid double encoding for URL. It may not be very apparent when looking in the IDE.
String url = "http://primesport.sieenasoftware.com/QryApi/GetEvents?";
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.add("username", "username");
params.add("password", "password");
params.add("userid", "23");
UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(url).queryParams(params).build();
System.out.println(uriComponents.toUri());
Please let me know, how it works out.
Also, please let know, if you cant find steps to setup fiddler proxy. It quite a handy tool, while coding the service clients.
According to the json format, all you need is using the Event class instead of the Result class.
Or change the JSON result to this :
["events": {
"EventId":1000250537,
"Name":"US Open Golf",
"SubTitle":null,
"Description":"US Open Golf Tickets",
"Date":"\/Date(1434873560000)\/",
"LocalDate":"6/20/2015 11:59 PM",
"LocalDateFrom":null,
"ImageUrl":null,
"VenueId":146566,
"Venue":"Chambers Bay Golf Course",
"AvailableTickets":33,
"PerformerId":151551,
"Performer":"US Open Golf",
"PerformerType":"Golf",
"SubcategoryId":55,
"UrlCategoryName":"Sports",
"MetaTitle":null,
"MetaDescription":null,
"PrimeSportUrl":"http://primesport.sieenasoftware.com/e/sports/us-open-golf/chambers-bay-golf-course/",
"SectionWiseView":null,
"VenueCity":"UNIVERSITY PLACE",
"VenueState":"WA",
"SnippetDate":null,
"EIProductionId":99985,
"RequireBillingAsShipping":false},
{
"EventId":1000253479,
"Name":"Womens College World Series",
"SubTitle":null,
"Description": .....
You can try importing Jackson Jar or add dependency in pom.xml if you are using Maven.
ObjectMapper mapper = new ObjectMapper();
try
{
mapper.writeValue(new File("c://temp/employee.json"), Results);
}

JSON mapping to Java returning null value

I'm trying to map JSON to Java using gson.I was succesful in writing the logic but unsuccesful in getting the output.Below posted are my JSON and Java files.Any help would be highly appreciated.
This is the output i'm getting
value:null
Below posted is the code for .json files
{
"catitem": {
"id": "1.196289",
"src": "http://feeds.reuters.com/~r/reuters/MostRead/~3/PV-SzW7Pve0/story06.htm",
"orig_item_date": "Tuesday 16 June 2015 07:01:02 PM UTC",
"cat_id": "1",
"heding": "Putin says Russia beefing up nuclear arsenal",
"summary": "KUvdfbefb bngfb",
"body": {
"bpart": [
"KUBINKA,dvdvdvdvgbtgfdnhfbnrtdfbcv dbnfg"
]
}
}
}
Below posted is my .java file
public class offc {
public static void main(String[] args) {
JsonReader jr = null;
try {
jr = new JsonReader(new InputStreamReader(new FileInputStream(
"C:\\Users\\rishii\\IdeaProjects\\rishi\\src\\file3.json")));
} catch (Exception ex) {
ex.printStackTrace();
}
Doll s = new Doll();
Gson g = new Gson();
Doll sr1 = g.fromJson(jr, Doll.class);
System.out.println(sr1);
}
}
Below posted is the code for Doll.java
class Doll {
private catitem ct;
public void setCt(catitem ct) {
this.ct = ct;
}
public catitem getCt() {
return ct;
}
#Override
public String toString()
{
return "value:" + ct;
}
class catitem {
private String id;
private String src;
private String orig_item_date;
private String cat_id;
private String heding;
private String summary;
private body ber;
catitem(String id, String src, String orig_item_date, String cat_id, String heding,
String summary) {
this.id = id;
this.src = src;
this.orig_item_date = orig_item_date;
this.cat_id = cat_id;
this.heding = heding;
this.summary = summary;
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setSrc(String src) {
this.src = src;
}
public String getSrc() {
return src;
}
public void setOrig_item_date(String Orig_item_date) {
this.orig_item_date = Orig_item_date;
}
public String getOrig_item_date() {
return getOrig_item_date();
}
public void setCat_id(String cat_id) {
this.cat_id = cat_id;
}
public String getCat_id() {
return cat_id;
}
public void setHeding(String heding) {
this.heding = heding;
}
public String getHeding() {
return heding;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getSummary() {
return summary;
}
public void setBer(body ber) {
this.ber = ber;
}
public body getBer() {
return ber;
}
#Override
public String toString() {
return "id:" + id + "cat_id" + cat_id + "summary" + summary + "orig_date"
+ orig_item_date + "heding" + heding;
}
}
class body {
private String bpart;
public void setBpart(String r) {
this.bpart = r;
}
public String getBpart() {
return bpart;
}
#Override
public String toString() {
return "hiii";
}
}
}
The issue is in class Doll, You have a field ct but in json catitem. Rename the field ct to catitem or if you are using Gson use #SerializedName("catitem") on filed ct and it will work.

Categories