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 :)
Related
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
I am have a problem in converting JSON String to Java object. As per my scenario Database (PostgreSQL) is returning JSON String in PGOBJECT through function.
Which I am trying to convert into model Class. Returned value JSON sample is:
{
"A_REASON": [
{
"cd": "CLOSE",
"name": "CLOSE",
"value": "A_REASON",
"type": "A_REASON"
}
],
"P_MODE": [
{
"cd": "CLOSE",
"name": "CLOSE",
"value": "A_REASON",
"type": "A_REASON"
}
],
"F_TYPE": [
{
"cd": "CLOSE",
"name": "CLOSE",
"value": "A_REASON",
"type": "A_REASON"
} ] }
I have created My Model Classes like below.
public class MODEL {
private List<MISCDTO> A_REASON;
private List<MISCDTO> P_MODE;
private List<MISCDTO> F_TYPE;
//settter and Getter
}
public class MISCDTO{
private String cd;
private String name;
private String value;
private String type;
}
When I am trying to convert into Model Class from JSON String it gives error, I have tried multiple ways
ObjectMapper mapper = new ObjectMapper();
MODEL object = mapper.readValue(pGobject.getValue(), MODEL.class);
List<MODEL> list = mapper.readValue(pGobject.getValue(), new TypeReference<List<MODEL >>(){});
MODEL object= mapper.readValue(pGobject.getValue(), new TypeReference<MODEL>() {});
I am looking to convert into either Map> or MODEL object having List, List etc. Please help. Please do help in Formatting as i am trying to Write in Stack Standard. Still novice on this.
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.
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
I am trying to convert a JSON array to a Java object, but I am having problems understanding how to use GSON.
The JSON array looks like this:
"[
{
"category": "1",
"checks": [
{
"check": "1.1",
"penaltypoints": "1.1",
"keypoint": "1.1"
},
{
"check": "1.2",
"penaltypoints": "1.2",
"keypoint": "1.2"
}
]
},
{
"category": "2",
"checks": [
{
"check": "2.1",
"penaltypoints": "2.1",
"keypoint": "2.1"
},
{
"check": "2.2",
"penaltypoints": "2.2",
"keypoint": "2.2"
}
]
}
]"
My corresponding Java classes are:
class Category {
public String description;
public List<Check> checks;
}
class Check {
public String description;
public float penaltyPoints;
public KeyPoint keypoint;
}
class KeyPoint {
public String description;
}
And this is how I called GSON:
Gson gson = new Gson();
Category categoriesArray[] = gson.fromJson(jsonString, Category[].class);
At the moment it is throwing up the following error:
Expected BEGIN_OBJECT but was STRING at line 1 column 125
I am new to GSON and am having problems understanding how it works. Can anyone please help me understand what I am doing wrong?
You're expecting this
"keypoint": "2.1"
to be mapped to
public KeyPoint keypoint;
...
class KeyPoint {
public String description;
}
In Java-JSON conversions, a POJO is meant to map to a JSON object and vice versa. Here, you're trying to map a JSON String to a POJO. That won't work by by default.
Either write and register your own TypeAdapter with Gson that will do this conversion or change your JSON to
"keypoint" : {
"description" : "2.1"
}