GSON from JSON nested object null pointer exception - java

I have the following JSON file:
{
“weight": {
"type": "weight",
"range": [
"2016-02-15",
"2016-02-16",
"2016-02-17",
"2016-02-18",
"2016-02-19",
"2016-02-20",
"2016-02-21"
],
"days": [
{
"weight": [
{
"bmi": 29.5,
"date": "2016-02-14",
"logId": 1455494399000,
"source": "API",
"time": "23:59:59",
"weight": 90.3
},
]
}
I then have the following classes that I want this JSON to be added to.
public class fitbitTypeWeight {
public fitbitDays weight;
}
public class fitbitDays {
public fitbitDayWeight days;
}
public class fitbitDayWeight {
public fitbitWeight weight;
}
public class fitbitDayWeight {
public fitbitWeight weight;
}
Then, I have the following code to try and parse it.
public static void readJSON() {
Gson gson = new Gson();
type = gson.fromJson(file, fitbitTypeWeight.class);
GsonBuilder builder = new GsonBuilder();
gson = builder.create();
createFitBitInfo();
}
private static void createFitBitInfo() throws ITrustException{
RemoteMonitoringDAO db = new RemoteMonitoringDAO(prodDAO);
RemoteMonitoringDataBean temp=new RemoteMonitoringDataBean();
fitbitDayWeight info = type.weight.days;
temp.setFitbitWeight(info.weight.weight);
temp.setFitbitDate(info.weight.date);
temp.setLoggedInMID(userID);
db.storeFitbitData(temp);
}
However, I am getting a NPE exception on fitbitDayWeight info = type.weight.days;
Any suggestions on what could be going wrong?

Your JSON is malformed. Looking just at the days element, we have:
"days": [
{
"weight": [
{
"bmi": 29.5,
"date": "2016-02-14",
"logId": 1455494399000,
"source": "API",
"time": "23:59:59",
"weight": 90.3
},
]
Looking at that, you've got:
dangling , on list weight
no closing ] on list weight
no closing } on 0 in list days
(To be complete, the if the final , were not there, ] would close weight then } would close object 0 in list days, leaving days and base unclosed.)
Also, you have a “ as your first quote instead of ". I don't know for sure if GSON is ok with angle quotes, but I know the JSON standard asks for " on all quotes.
I'm honestly slightly surprised GSON doesn't spit errors on load because of this. But the reason you're getting a NullPointerException is because type.weight.days is set to the default value because GSON couldn't read a value for it.

Related

How to make com.fasterxml.jackson print array vertically? [duplicate]

I have data that looks like this:
{
"status": "success",
"data": {
"irrelevant": {
"serialNumber": "XYZ",
"version": "4.6"
},
"data": {
"lib": {
"files": [
"data1",
"data2",
"data3",
"data4"
],
"another file": [
"file.jar",
"lib.jar"
],
"dirs": []
},
"jvm": {
"maxHeap": 10,
"maxPermSize": "12"
},
"serverId": "134",
"version": "2.3"
}
}
}
Here is the function I'm using to prettify the JSON data:
public static String stringify(Object o, int space) {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(o);
} catch (Exception e) {
return null;
}
}
I am using the Jackson JSON Processor to format JSON data into a String.
For some reason the JSON format is not in the format that I need. When passing the data to that function, the format I'm getting is this:
{
"status": "success",
"data": {
"irrelevant": {
"serialNumber": "XYZ",
"version": "4.6"
},
"another data": {
"lib": {
"files": [ "data1", "data2", "data3", "data4" ],
"another file": [ "file.jar", "lib.jar" ],
"dirs": []
},
"jvm": {
"maxHeap": 10,
"maxPermSize": "12"
},
"serverId": "134",
"version": "2.3"
}
}
}
As you can see under the "another data" object, the arrays are displayed as one whole line instead of a new line for each item in the array. I'm not sure how to modify my stringify function for it to format the JSON data correctly.
You should check how DefaultPrettyPrinter looks like. Really interesting in this class is the _arrayIndenter property. The default value for this property is FixedSpaceIndenter class. You should change it with Lf2SpacesIndenter class.
Your method should looks like this:
public static String stringify(Object o) {
try {
ObjectMapper mapper = new ObjectMapper();
DefaultPrettyPrinter printer = new DefaultPrettyPrinter();
printer.indentArraysWith(new Lf2SpacesIndenter());
return mapper.writer(printer).writeValueAsString(o);
} catch (Exception e) {
return null;
}
}
I don't have enough reputation to add the comment, but referring to the above answer Lf2SpacesIndenter is removed from the newer Jackson's API (2.7 and up), so instead use:
printer.indentArraysWith(DefaultIndenter.SYSTEM_LINEFEED_INSTANCE);
Source of the solution

Jackson - ReadValue fails

UPDATE! Fixed, there was a missed public statement on prices attribute that was the reason this error occurred.
I am trying out Jackson for converting between .json files and objects. However, I keep receiving this error "UnrecognizedPropertyException: Unrecognized field "Prices" (class imp.JsonDTO), not marked as ignorable (one known property: "Ticker"]" .
I am trying to convert a json file that looks like this:
{
"Ticker": "AAPL",
"Prices": [
{
"Date": "1986-01-02T00:00:00",
"Value": 22.25,
"Action": "Sell"
},
{
"Date": "1986-01-03T00:00:00",
"Value": 22.38,
"Action": "Buy"
},
{
"Date": "1986-01-06T00:00:00",
"Value": 22.38,
"Action": "Sell"
}
]
}
I am converting like this:
ObjectMapper mapper = new ObjectMapper();
File file = new File("INTC.json");
JsonDTO dto = mapper.readValue(file, JsonDTO.class);
DTO's that I am using:
public class JsonDTO {
public String Ticker;
List<PriceDTO> Prices = new ArrayList<PriceDTO>();
}
and..
public class PriceDTO {
public String Date;
public double Value;
public String Action;
}
Tried a few different ways for "Prices" but seem unable to get it right.Thanks for help :)

Parsing JSON in java: Malformed JSON: Unexpected 'C'

Good day,
I am parsing some JSON in java (a notification from a cisco CMX system). I've parsed a lot of JSON in my time but this one refuses to get parsed. I've tried several methods: a reader with lenient mode, plain gson, etc.
The JSON I parse is valid according to jsonlint, which leads me to believe it is a problem with the parser, or maybe some hidden characters that I am unable to sanitize out. This is the JSON I receive:
{
"startTime": "08:00",
"previousEndDate": null,
"startDate": "2016-02-17",
"title": "Visitors",
"executionTime": 29,
"value": {
"primary": {
"title": "TotalVisitors",
"value": 16,
"peakValue": 0,
"breakdown": [{
"title": "RepeatVisitors",
"value": 11
}, {
"title": "NewVisitors",
"value": 5
}]
},
"average": {
"title": "TotalVisitors",
"value": 19,
"peakValue": 0,
"breakdown": [{
"title": "RepeatVisitors",
"value": 15
}, {
"title": "NewVisitors",
"value": 4
}]
},
"previousTimeRange": {
"title": "TotalVisitors",
"value": 23,
"peakValue": 0,
"breakdown": [{
"title": "RepeatVisitors",
"value": 19
}, {
"title": "NewVisitors",
"value": 4
}]
}
},
"areas": [{
"id": 20,
"name": "CineCitta"
}],
"previousStartDate": "2016-02-16",
"endDate": null,
"endTime": "09:29"
}
It seems valid to me, and the object I try to parse it into has the correct fields.
I've tried filtering out \r \t \n \0 and some combinations between them.
The code I currently have in java is:
String result = "{\"startTime\":\"08:00\",\"previousEndDate\":null,\"startDate\":\"2016-02-17\",\"title\":\"Visitors\",\"executionTime\":29,\"value\":{\"primary\":{\"title\":\"TotalVisitors\",\"value\":16,\"peakValue\":0,\"breakdown\":[{\"title\":\"RepeatVisitors\",\"value\":11},{\"title\":\"NewVisitors\",\"value\":5}]},\"average\":{\"title\":\"TotalVisitors\",\"value\":19,\"peakValue\":0,\"breakdown\":[{\"title\":\"RepeatVisitors\",\"value\":15},{\"title\":\"NewVisitors\",\"value\":4}]},\"previousTimeRange\":{\"title\":\"TotalVisitors\",\"value\":23,\"peakValue\":0,\"breakdown\":[{\"title\":\"RepeatVisitors\",\"value\":19},{\"title\":\"NewVisitors\",\"value\":4}]}},\"areas\":[{\"id\":20,\"name\":\"CineCitta\"}],\"previousStartDate\":\"2016-02-16\",\"endDate\":null,\"endTime\":\"09:29\"}";
JsonReader reader = new JsonReader(new StringReader(result));
reader.setLenient(true);
Gson gson = new Gson();
ClientInfo info = gson.fromJson(reader, ClientInfo.class);
The question is: Does anyone know how to debug a problem like this? are there sanitization techniques I can use? Other parsers?
EDIT: The code to clientinfo as requested (using project lombok, all fields are public):
#ToString
#FieldDefaults(level = AccessLevel.PUBLIC)
public class ClientInfo {
String startTime;
String previousEndDate;
String startDate;
String title;
Integer executionTime;
Value value;
Area [] areas;
String previousStartDate;
String endDate;
String endTime;
}
public class Value {
public Visitors primary;
public Visitors average;
public Visitors previousTimeRange;
}
#FieldDefaults(level = AccessLevel.PUBLIC)
public class Area {
Integer id;
String name;
}
#FieldDefaults(level = AccessLevel.PUBLIC)
public class Visitors {
String title;
Integer value;
Integer peakValue;
Record [] breakdown;
}
public class Record {
public String title;
public Integer value;
}
Thanks and good day
String result = "{\"startTime\":\"08:00\",\"previousEndDate\":null,\"startDate\":\"2016-02-17\",\"title\":\"Visitors\",\"executionTime\":29,\"value\":{\"primary\":{\"title\":\"TotalVisitors\",\"value\":16,\"peakValue\":0,\"breakdown\":[{\"title\":\"RepeatVisitors\",\"value\":11},{\"title\":\"NewVisitors\",\"value\":5}]},\"average\":{\"title\":\"TotalVisitors\",\"value\":19,\"peakValue\":0,\"breakdown\":[{\"title\":\"RepeatVisitors\",\"value\":15},{\"title\":\"NewVisitors\",\"value\":4}]},\"previousTimeRange\":{\"title\":\"TotalVisitors\",\"value\":23,\"peakValue\":0,\"breakdown\":[{\"title\":\"RepeatVisitors\",\"value\":19},{\"title\":\"NewVisitors\",\"value\":4}]}},\"areas\":[{\"id\":20,\"name\":\"CineCitta\"}],\"previousStartDate\":\"2016-02-16\",\"endDate\":null,\"endTime\":\"09:29\"}";
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonObject jsonObj = parser.parse(result).getAsJsonObject();
ClientInfo info = gson.fromJson( jsonObj , ClientInfo.class);
You can give a try with above code.
I am a dumdum.
I assumed the parsing was what went wrong, but it was actually that my service was supposed to produce a JSON, where I did not return it as json, but the object itself resulting in a bad parsing.
Because I was so focused on the parsing I was doing I did not realize the error itself occurred on the implicit json parsing of the restful service.
That'll teach me not to test in a simple environment before moving my code to the a restful client.
Thanks and dumb greetings,
Dries

how to parse this nested json using gson

I have this json as a string (this is from google custom search). I have made equivalent java classes that are neccessary to parse this. I use gson and am getting a NullPointerException.
"items": [
{
"kind": "customsearch#result",
"title": "A Florida Road Trip - Articles | Travel + Leisure",
"htmlTitle": "A \u003cb\u003eFlorida\u003c/b\u003e Road Trip - \u003cb\u003eArticles\u003c/b\u003e | Travel + Leisure",
"link": "http://www.travelandleisure.com/articles/paradise-usa",
"displayLink": "www.travelandleisure.com",
"snippet": "On a road trip across Florida, Karrie Jacobs goes in search of the authentic amid New Urbanist experiments in postmodern nostalgia.",
"htmlSnippet": "On a road trip across \u003cb\u003eFlorida\u003c/b\u003e, Karrie Jacobs goes in search of the authentic amid \u003cbr\u003e New Urbanist experiments in postmodern nostalgia.",
"cacheId": "QrfYt6p-U3gJ",
"formattedUrl": "www.travelandleisure.com/articles/paradise-usa",
"htmlFormattedUrl": "www.travelandleisure.com/\u003cb\u003earticles\u003c/b\u003e/paradise-usa",
"pagemap": {
"cse_image": [
{
"src": "http://static0.travelandleisure.com/images/amexpub/0000/6261/200702_urban.jpg"
}
],
"cse_thumbnail": [
{
"width": "160",
"height": "200",
"src": "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcR_Jhmej45Lu7L3bQoKz1poITJ5ZeuVvKhH62myfBOj-1VEX9oqwIhvH74"
}
],
"metatags": [
{
"fb:app_id": "145695458805001",
"og:url": "http://www.travelandleisure.com/articles/paradise-usa",
"og:site_name": "Travel + Leisure",
"og:image": "http://static0.travelandleisure.com/images/amexpub/0000/6261/200702_urban.jpg",
"og:type": "article",
"og:title": "Driving: Florida’s New Urbanist Experiments",
"og:description": "On a road trip across Florida, Karrie Jacobs goes in search of the authentic amid New Urbanist exper..."
}
]
}
}
And my equivalent java classes are as follows:
public Class Mapper
{
public Items[] items;
}
public Class Items
{
public String title;
public String htmlSnippet;
public String link;
public Pagemap pagemap;
}
public Class Pagemap
{
public Cse_image[] image;
}
public Class Cse_image
{
public String src;
}
public Class Parser
{
public static void main(String[] args)
{
//assume json is the string representation of the above json
Gson gson = new GsonBuilder().create();
Mapper mapper= gson.fromJson(json,Mapper.class);
System.out.println("src here"+mapper.items[0].pagemap.image[0].src);
}
}
The above code throws me a NullPointerException , but if I print till the pagemap ,I get an object with a valid hashcode. Any pointers?
Whenever dealing with JSON, it is a good practice to use a LINT software to verify the contents of JSON. I recommend using jsonlint.com. The JSON list shows multiple errors in the JSON string. Running some REPL cycles here is the corrected JSON.
{
"items": [
{
"kind": "customsearch#result",
"title": "AFloridaRoadTrip-Articles|Travel+Leisure",
"htmlTitle": "A<b>Florida</b>RoadTrip-<b>Articles</b>|Travel+Leisure",
"link": "http: //www.travelandleisure.com/articles/paradise-usa",
"displayLink": "www.travelandleisure.com",
"snippet": "OnaroadtripacrossFlorida,KarrieJacobsgoesinsearchoftheauthenticamidNewUrbanistexperimentsinpostmodernnostalgia.",
"htmlSnippet": "Onaroadtripacross<b>Florida</b>,KarrieJacobsgoesinsearchoftheauthenticamid<br>NewUrbanistexperimentsinpostmodernnostalgia.",
"cacheId": "QrfYt6p-U3gJ",
"formattedUrl": "www.travelandleisure.com/articles/paradise-usa",
"htmlFormattedUrl": "www.travelandleisure.com/<b>articles</b>/paradise-usa",
"pagemap": {
"cse_image": [
{
"src": "http: //static0.travelandleisure.com/images/amexpub/0000/6261/200702_urban.jpg"
}
],
"cse_thumbnail": [
{
"width": "160",
"height": "200",
"src": "https: //encrypted-tbn1.gstatic.com/images?q=tbn: ANd9GcR_Jhmej45Lu7L3bQoKz1poITJ5ZeuVvKhH62myfBOj-1VEX9oqwIhvH74"
}
],
"metatags": [
{
"fb: app_id": "145695458805001",
"og: url": "http: //www.travelandleisure.com/articles/paradise-usa",
"og: site_name": "Travel+Leisure",
"og: image": "http: //static0.travelandleisure.com/images/amexpub/0000/6261/200702_urban.jpg",
"og: type": "article",
"og: title": "Driving: Florida’sNewUrbanistExperiments",
"og: description": "OnaroadtripacrossFlorida,KarrieJacobsgoesinsearchoftheauthenticamidNewUrbanistexper..."
}
]
}
}
]
}
First rename your class Cse_Image to a more conventional java name (CseImage maybe?), same for the thumbnail class.
Then you can try genson library http://code.google.com/p/genson/.
Put #JsonProperty("cse_image") annotation on your image field (or on your setter/getter if you have) and it works :
Genson genson = new Genson();
Mapper mapper= genson.deserialize(json,Mapper.class);
System.out.println("src here"+mapper.items[0].pagemap.image[0].src);

Gson help with parse array - works without array but won't with array

Can somebody help me with Gson parser. When I remove change from JSON and Result it works fine but with change it throws JsonParseException-Parse failed.
Result[] response = gson.fromJson(fileData.toString(), Result[].class);
I have classes like this
public class Result {
public String start_time;
public String end_time;
public change[] change;
}
and
public class change {
public String id;
public String name;
}
and Json string like
[
{
"start_time": "8:00",
"end_time": "10:00",
"change": [
{
"id": "1",
"name": "Sam"
},
{
"id": "2",
"name": "John"
}
]
},
{
"start_time": "9:00",
"end_time": "15:00",
"change": [
{
"id": "1",
"name": "Sam"
},
{
"id": "2",
"name": "John"
}
]
}
]
Can somebody tell me what I did wrong ? Any idea why it won't work with array ?
As has been suggested, you need to use a list instead. Gson has pretty good documentation for using parametized types with the parser, you can read more about it here. Your code will end up looking like this:
Type listType = new TypeToken<List<Result>>() {}.getType();
List<Result> results = gson.fromJson(reader, listType);
for (Result r : results) {
System.out.println(r);
}

Categories