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.
Related
i really ned help with this. Im not being able to read the JSON and i dont know what im doing wrong.
I will drop my code here.
I have this Json
{
"id": "288",
"name": "Tarjeta Shopping",
"secure_thumbnail": "https://www.mercadopago.com/org-img/MP3/API/logos/288.gif",
"thumbnail": "http://img.mlstatic.com/org-img/MP3/API/logos/288.gif",
"processing_mode": "aggregator",
"merchant_account_id": null
}
This is my class that should represent that JSON
public class Tarjeta {
#SerializedName("id")
#Expose
private String id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("secure_thumbnail")
#Expose
private String secureThumbnail;
#SerializedName("thumbnail")
#Expose
private String thumbnail;
#SerializedName("processing_mode")
#Expose
private String processingMode;
#SerializedName("merchant_account_id")
#Expose
private Object merchantAccountId;
public Tarjeta() {
}
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;
}
public String getSecureThumbnail() {
return secureThumbnail;
}
public void setSecureThumbnail(String secureThumbnail) {
this.secureThumbnail = secureThumbnail;
}
public String getThumbnail() {
return thumbnail;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
public String getProcessingMode() {
return processingMode;
}
public void setProcessingMode(String processingMode) {
this.processingMode = processingMode;
}
public Object getMerchantAccountId() {
return merchantAccountId;
}
public void setMerchantAccountId(Object merchantAccountId) {
this.merchantAccountId = merchantAccountId;
}
#Override
public String toString() {
return "Tarjeta{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", secureThumbnail='" + secureThumbnail + '\'' +
", thumbnail='" + thumbnail + '\'' +
", processingMode='" + processingMode + '\'' +
", merchantAccountId=" + merchantAccountId +
'}';
}
}
this is my GET method
#GET("payment_methods/card_issuers")
Call<Tarjeta> getTarjetas2(#Query("public_key") String apiKey,
#Query("payment_method_id") String payment_method_id);
And this is where i try to read it.
botonTest2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("Test boton 2 clickeado");
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
ServicePago servicePago = retrofit.create(ServicePago.class);
Call<Tarjeta> contenedorTarjetaCall = servicePago.getTarjetas2(apiKey,"visa");
contenedorTarjetaCall.enqueue(new Callback<Tarjeta>() {
#Override
public void onResponse(Call<Tarjeta> call, Response<Tarjeta> response) {
Toast.makeText(MainActivity.this, "BIEN", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<Tarjeta> call, Throwable t) {
Toast.makeText(MainActivity.this, "ALGO SALIO MAL", Toast.LENGTH_SHORT).show();
}
});
}
});
Im habing this error: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
I think my class is correctly modelated, im completly lost.
since you did not post your entire JSON I'm going to answer with a rough idea hope it helps.
the error states that the received JSON is not a Tarjeta but an array of Tarjeta. so to fix it I guess you just have to wrap your response in a list type. so it goes something like this:
#GET("payment_methods/card_issuers")
Call<List<Tarjeta>> getTarjetas2(#Query("public_key") String apiKey,
#Query("payment_method_id") String payment_method_id);
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.
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.
I have been trying to get this over for a while now with little or no success. Right now, I am really out of options. I will appreciate some assistance or pointers towards the right direction.... since I believe I am not doing somethings very well.
After parsing with the code below, I have null values in most of the fields: Result{id=30c26c8a-8bdf-4d4d-8f8d-a19661f16877, name=Andriod_Office_Task, owner =generated.Owner#53d8d10a, comment=, creationTime=2016-09-09T19:30, modificationTime=2016-09-09T19:30:05+02:00, reportId=null, taskid=null, host=null, port=null, nvt=null, scanNVTVersion=null, threat=null, severity=null, description=null}
The parsing methods (other methods are excluded for brevity):
private List<Result> readDocument(XMLStreamReader parser) throws XMLStreamException, DatatypeConfigurationException {
List<Result> results = new ArrayList<>();
while (parser.hasNext()) {
int eventType = parser.next();
switch (eventType) {
case XMLStreamReader.START_ELEMENT:
String elementName = parser.getLocalName();
if (elementName.equals("result"))
results.add(readResult(parser));
break;
case XMLStreamReader.END_ELEMENT:
return results;
}
}
throw new XMLStreamException("Premature end of file");
}
public Result readResult(XMLStreamReader parser) throws XMLStreamException, DatatypeConfigurationException {
Result result = new Result();
result.setId(parser.getAttributeValue(null, "id"));
Report report = new Report();
Task task = new Task();
while (parser.hasNext()) {
int eventType = parser.next();
switch (eventType) {
case XMLStreamReader.START_ELEMENT:
String elementName = parser.getLocalName();
if (elementName.equals("name"))
result.setName(readCharacters(parser));
else if (elementName.equals("host"))
result.setHost(readCharacters(parser));
else if (elementName.equals("owner"))
result.setOwner(readOwner(parser));
else if (elementName.equals("comment"))
result.setComment(readCharacters(parser));
else if (elementName.equals("creation_time"))
result.setCreationTime(readCreationTime(parser));
else if (elementName.equals("modification_time"))
result.setModificationTime(readCharacters(parser));
else if (elementName.equals("report"))
report.setId(readReport(parser));
else if (elementName.equals("task"))
task.setId(readTask(parser));
else if (elementName.equals("user_tags"))
result.setUserTags(readUserTags(parser));
else if (elementName.equals("port"))
result.setPort(readCharacters(parser));
else if (elementName.equals("nvt"))
result.setNvt(readNvt(parser));
else if (elementName.equals("scan_nvt_version"))
result.setScanNVTVersion(readCharacters(parser));
else if (elementName.equals("threat"))
result.setThreat(readCharacters(parser));
else if (elementName.equals("severity"))
result.setSeverity(readCharacters(parser));
else if (elementName.equals("qod"))
result.setQod((Qod) readQod(parser));
else if (elementName.equals("description"))
result.setDescription(readCharacters(parser));
break;
case XMLStreamReader.END_ELEMENT:
}
return result;
}
throw new XMLStreamException("Premature end of file");
}
private String readCharacters(XMLStreamReader reader) throws XMLStreamException {
StringBuilder result = new StringBuilder();
while (reader.hasNext()) {
int eventType = reader.next();
switch (eventType) {
case XMLStreamReader.CHARACTERS:
result.append(reader.getText());
break;
case XMLStreamReader.END_ELEMENT:
return result.toString();
}
}
throw new XMLStreamException("Premature end of file");
}
}
The result class is below :
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
#JsonIgnoreProperties(ignoreUnknown = true)
public class Result {
#XmlAttribute
private String id;
#XmlElement
private String name;
#XmlElement
private Task task;
#XmlElement
private String comment;
#XmlElement(name = "creation_time")
String creationTime;
#XmlElement(name = "modification_time")
private String modificationTime;
// TODO user_tags
#XmlElement
private UserTags userTags;
#XmlElement
private Owner owner;
#XmlElement
private Qod qod;
/**
* // * The report the result belongs to (only when details were requested)
* //
*/
#XmlElementWrapper(name = "report")
#XmlElement(name = "reportId")
private String reportId;
#XmlElement
private String host;
#XmlElement
private String port;
#XmlElement
private NVT nvt;
#XmlElement(name = "scan_nvt_version")
private String scanNVTVersion;
#XmlElement
private String threat;
#XmlElement
private String severity;
#XmlElement
private String description;
public Result() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Task getTask() {
return task;
}
public void setTask(Task task) {
this.task = task;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getCreationTime() {
return creationTime;
}
public void setCreationTime(String creationTime) {
this.creationTime = creationTime;
}
public String getModificationTime() {
return modificationTime;
}
public void setModificationTime(String modificationTime) {
this.modificationTime = modificationTime;
}
public UserTags getUserTags() {
return userTags;
}
public void setUserTags(UserTags userTags) {
this.userTags = userTags;
}
public Qod getQod() {
return qod;
}
public void setQod(Qod qod) {
this.qod = qod;
}
public Owner getOwner() {
return owner;
}
public void setOwner(Owner owner) {
this.owner = owner;
}
public String getReportId() {
return reportId;
}
public void setReportId(String reportId) {
this.reportId = reportId;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public NVT getNvt() {
return nvt;
}
public void setNvt(NVT nvt) {
this.nvt = nvt;
}
public String getScanNVTVersion() {
return scanNVTVersion;
}
public void setScanNVTVersion(String scanNVTVersion) {
this.scanNVTVersion = scanNVTVersion;
}
public String getThreat() {
return threat;
}
public void setThreat(String threat) {
this.threat = threat;
}
public String getSeverity() {
return severity;
}
public void setSeverity(String severity) {
this.severity = severity;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "Result{" + "id=" + id +
", name=" + name + ", owner =" + owner +
", comment=" + comment + ", creationTime=" + creationTime + ", modificationTime=" + modificationTime
+ ", reportId=" + reportId + ", taskid=" + task + ", host=" + host + ", port=" + port + ", nvt=" + nvt
+ ", scanNVTVersion=" + scanNVTVersion + ", threat=" + threat + ", severity=" + severity
+ ", description=" + description + '}';
}
}
<get_results_response status="200" status_text="OK">
<result id="30c26c8a-8bdf-4d4d-8f8d-a19661f16877">
<name>Trace route</name>
<owner>
<name>admin</name>
</owner>
<comment/>
<creation_time>2016-09-09T19:30:05+02:00</creation_time>
<modification_time>2016-09-09T19:30:05+02:00</modification_time>
< id="2a6d7f75-f6b7-40b2-a792-b558fada375b"/>
<task id="e59ac66b-5b59-4756-bace-37bb1106276d">
<name>Andriod_Office_Task</name>
</task>
<user_tags>
<count>0</count>re
</user_tags>
<host>172.16.53.178</host>
<port>general/tcp</port>
<nvt oid="1.3.6.1.4.1.25623.1.0.51662">
<name>Traceroute</name>
<family>General</family>
<cvss_base>0.0</cvss_base>
<cve>NOCVE</cve>
<bid>NOBID</bid>
<xref>NOXREF</xref>
<tags>cvss_base_vector=AV:N/AC:L/Au:N/C:N/I:N/A:N|qod_type=remote_banner|solution=Block unwanted packets from escaping your network.|summary=A traceroute from the scanning server to the target system was
conducted. This traceroute is provided primarily for informational
value only. In the vast majority of cases, it does not represent a
vulnerability. However, if the displayed traceroute contains any
private addresses that should not have been publicly visible, then you
have an issue you need to correct.</tags>
<cert/>
</nvt>
<scan_nvt_version>$Revision: 2837 $</scan_nvt_version>
<threat>Log</threat>
<severity>0.0</severity>
<qod>
<value>80</value>
<type>remote_banner</type>
</qod>
<description>Here is the route from 192.168.14.128 to 172.16.53.178:
192.168.14.128
172.16.53.178</description>
</result>
<filters id="">
<term>first=1 rows=-1 sort=name</term>
<keywords>
<keyword>
<column>first</column>
<relation>=</relation>
<value>1</value>
</keyword>
<keyword>
<column>rows</column>
<relation>=</relation>
<value>-1</value>
</keyword>
<keyword>
<column>sort</column>
<relation>=</relation>
<value>name</value>
</keyword>
</keywords>
</filters>
<sort>
<field>name
<order>ascending</order></field>
</sort>
<results max="-1" start="1"/>
<result_count>3444
<filtered>1</filtered>
<page>1</page></result_count>
</get_results_response>
After some research and attempts with some common xml parsing approaches, I ended up using jackson-dataformat-xml approach. While this might not be the best it gave me what I wanted with much less code. Basically, I had to adapt the annotations in the model classes as below :
#JsonIgnoreProperties(ignoreUnknown=true)
#JacksonXmlRootElement(localName = "results")
public class Results {
#JacksonXmlProperty(localName = "result")
#JacksonXmlElementWrapper(useWrapping = false)
public Result [] result;
public Results() {
}
public Result[] getResult() {
return result;
}
public void setResult(Result[] result) {
this.result = result;
}
#Override
public String toString() {
return "Results [result=" + Arrays.toString(result) + "]";
}
And some adaptations for the parsing class:
public class GetReportsResponseHandler extends DefaultHandler<GetReportsResponse> {
private XmlMapper mapper = new XmlMapper();
public GetReportsResponseHandler() {
super(new GetReportsResponse(), "get_reports_response");
AnnotationIntrospector primary = new JacksonAnnotationIntrospector();
AnnotationIntrospector secondary = new JaxbAnnotationIntrospector();
AnnotationIntrospector pair = new AnnotationIntrospectorPair(primary, secondary);
mapper.setAnnotationIntrospector(pair);
}
#Override
protected void parseStartElement(XMLStreamReader parser) throws XMLStreamException, IOException {
if ("report".equals(parser.getName().toString())){
Report report = mapper.readValue(parser, Report.class);
response.addReport(report);
}
The error code :
org.codehaus.jackson.map.exc.UnrecognizedPropertyException:
Unrecognized field "id" (Class JacksonTester$Student), not
marked as ignorable
at [Source: [B#40334c25; line: 2, column: 8]
(through reference chain: Student["id"])
I have the below JSON file:
{
"id": "0",
"title": "0",
"externalId": "0",
"externalLink": "0",
"sourceApplication": "0",
"content": "0",
"summaryContent": "0",
"publishedDate": "0",
"harvestDate": "0",
"languageId": "0",
"regionId": "0",
"postStatus": "0"
}
and my code is
JacksonTester.java:
public class JacksonTester {
public static void main(String args[]) {
ObjectMapper mapper = new ObjectMapper();
// map json to student
try {
byte[] jsonData = Files.readAllBytes(Paths.get("output_json.txt"));
Student student = mapper.readValue(jsonData, Student.class);
System.out.println(student);
} catch (Exception e) {
e.printStackTrace();
}
}
static class Student {
String id;
String title;
String externalId;
String externalLink;
String sourceApplication;
String content;
String summaryContent;
String publishedDate;
String harvestDate;
String languageId;
String regionId;
String postStatus;
public Student() {
}
}
}
You need to either have setters for those fields or a constructor that accepts those fields as parameters (+ approriate annotations or -parameters from Java 8 and jackson-module-parameter-names
module):
public static class Student {
...
String postStatus;
public setPostStatus(postStatus) {
this.postStatus = postStatus;
}
...
}
Jackson has no access to the fields of Student.
Implement the public getters and setters for Student and it works.
I sorted this problem and it's working fine. Here is my code for the same.
**MainClass.java:**
public class MainClass {
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
String jsonStr = "{\r\n" + " \"id\": \"168\",\r\n" + " \"title\": \"Mr\",\r\n"
+ " \"externalId\": \"247518\",\r\n" + " \"externalLink\": \"www.gmail.com\",\r\n"
+ " \"sourceApplication\": \"adsense\",\r\n" + " \"content\": \"hmtl\",\r\n"
+ " \"summaryContent\": \"null\",\r\n" + " \"publishedDate\": \"12122018\",\r\n"
+ " \"harvestDate\": \"12122018\",\r\n" + " \"languageId\": \"3\",\r\n" + " \"regionId\": \"45\",\r\n"
+ " \"postStatus\": \"1\"\r\n" + "}";
ObjectMapper mapper = new ObjectMapper();
MyPojo details = mapper.readValue(jsonStr, MyPojo.class);
System.out.println("Value for getId is: " + details.getId());
System.out.println("Value for getSourceApplication is: " + details.getSourceApplication());
System.out.println("Value for getExternalId is: " + details.getPublishedDate());
System.out.println("Value for getExternalLink is: " + details.getExternalLink());
} }
**MyPojo.class**
public class MyPojo {
private String content;
private String id;
private String sourceApplication;
private String title;
private String postStatus;
private String publishedDate;
private String summaryContent;
private String harvestDate;
private String languageId;
private String externalId;
private String regionId;
private String externalLink;
public String getContent() {
return content;
}
public String getId() {
return id;
}
public String getSourceApplication() {
return sourceApplication;
}
public String getTitle() {
return title;
}
public String getPostStatus() {
return postStatus;
}
public String getPublishedDate() {
return publishedDate;
}
public String getSummaryContent() {
return summaryContent;
}
public String getHarvestDate() {
return harvestDate;
}
public String getLanguageId() {
return languageId;
}
public String getExternalId() {
return externalId;
}
public String getRegionId() {
return regionId;
}
public String getExternalLink() {
return externalLink;
} }
**RESULT:**
Value for getId is: 168
Value for getSourceApplication is: adsense
Value for getExternalId is: 12122018
Value for getExternalLink is: www.gmail.com
NOTE
One has to change the fields in the json to begin with a lower case letter. The reason for the JSON change is that the Jackson bean serialisation will reflect over the class, and when it sees getXyz() and setXyz() methods will map these to a Json filed names "xyz" (and not "Xyz").I think there are several ways to override this behaviour, one is to use the one of the Jackson annotations.
Instead of creating so many public getters, you could simply modify private variables to public