I have this JSON data, and I was wondering how I might convert this data to a Java POJO object:
"progression": {
"64693": [
{
"1": 1
}
],
"64717": [
{
"1": 4
}
]
},
I was thinking it can't be:
public class Progression{
private List<64693> 64693;
private List<64717> 64717;
public List<64693> get64693(){
return this.64693;
}
public void set64693(List<64693> 64693){
this.64693 = 64693;
}
public List<64717> get64717(){
return this.64717;
}
public void set64717(List<64717> 64717){
this.64717 = 64717;
}
}
I'm very familiar with Java, so I know I can do a #JsonProperty instead of the actual numbers, but just wondering if there were any other choices.
Thanks!
_ug had the right suggestion:
... object consider naming 64693 to like DataType64693 and adding the
#JsonProperty("64693") annotation
That worked fine. And BTW, I am using the Jackson 2.0 JSON processor.
Related
I have the following json file:
{
"authors":
[{"id":"author7",
"book":[
[
{
"value":{"pages":123}}]]},
{
"id": "author3",
"book": [
[
{
"value": {
"title": "LOTR"
}
},
{
"value": {
"boolean": false
}
},
],
[
{
"value": {
"pages": 350
}
},
{
"value": {
"boolean": false
}
},
],
[
{
"value": {
"boolean": false
}
},
{
"value": {
"pages": 150
}
},
]
]
},
}
I want to be able to create an object of Author but I am having problems while mapping the Json file with the Java classes I have created.
I understand that, while mapping the json file with the java classes, Authors class should have as fields
public class Authors{
private String authorId;
private Book book;
}
Class Book should be like this
public class Book {
private List<Values> values
public Book() {
}
}
But what about class Values?
public class Values{
private int pages;
private Boolean bool;
private String title;
public Values() {
}
}
Is this the correct way to map it? Because I see that if I create an object of Values it will ask me to modify the constructor or create a new constructor for each different object that comes from Json
Thank you for reading and helping!
Easy way out would to be to define Values by type 'object' as,
public class Book {
private List<Object> values
}
This way you won't run into the issue of having properties with null values when they don't exist in the JSON. Also, the JSON would be entirely parsed into an object even if new properties are get introduced (or which may not be defined under values class, as you have done above causing those not being mapped to the object).
However, when you are using 'object', be mindful with your logic that uses this parsed object. Although, you are assured to access the properties from the object as in the JSON, you will have to conditionally check whether the nessacary property exists first in each logical context to avoid possible undefined value errors.
This question is a follow up of this question .
Again, I am completely new to Java and JSON, so I don't know much at all. I was able to proceed a little further with the answers from the question mentioned above, but now I have encountered more issues, namely (basically) the syntax of how to return the list of multiple JSON. (I got these codes from SpringBoot, and I really don't know how it all works; I am still learning Java.)
Currently, this is what I've tried:
#GetMapping("reports/{userID}")
public ResponseEntity<LookupResponseList> getDirectReports(#PathVariable String userID) {
Optional<List<LDAPModel>> ldapModel = ldapService.getDirectReports(userID);
if (!ldapModel.isPresent()) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
LookupResponseResultList result = ldapMapper.toLookupResponseResultList(ldapModel.get());
return ResponseEntity.ok(LookupResponseList.result(result, LookupResponseList.class));
}
But I don't know how to return the list in the code above, on the line where I am trying to get the result:
LookupResponseResultList result = ldapMapper.toLookupResponseResultList(ldapModel.get());
The code for ldapMapper.toLookupResponseResultList is below:
public LookupResponseResultList toLookupResponseResultList(List<LDAPModel> ldapModel) {
return LookupResponseResultList.builder()
.userId(ldapModel.toString())
// .userId(ldapModel.getUserId())
// .telephoneNumber(ldapModel.getTelephoneNumber())
.build();
}
The two commented line is what I want. I can see the entire JSON structure in the line above the commentted line, which is this:
{
"result": {
"userId": "[LDAPModel(userId=abcde123,telephoneNumber=1-555-5555555), LDAPModel(userId=fghi456,telephoneNumber=1-333-3333333)]",
},
"error": null
}
How can I make it so that toLookupResponseResultList return a list of multiple JSON (like below) instead of a string?
{
"result": [
{
"userId": "abcde123",
"telephoneNumber": "1-555-5555555"
},
{
"userId": "fghi456",
"telephoneNumber": "1-333-3333333"
}
],
"error": null
}
Edit: LookupResponseResultList class is below:
public class LookupResponseList extends BaseBodyResponse<LookupResponseList.LookupResponseResultList> {
#Data
#Builder
#NoArgsConstructor
#AllArgsConstructor
public static class LookupResponseResultList {
String userId;
String telephoneNumber;
}
The problem is at -
public LookupResponseResultList toLookupResponseResultList(List<LDAPModel> ldapModel) {
return LookupResponseResultList.builder()
.userId(ldapModel.toString()) // THIS LINE
.build();
}
This LookupResponseResultList class must accept a List of LDAPModel objects.
class LookupResponseResultList {
#JsonProperty
private List<LDAPModel> result;
private String error.
}
Modify your builder and instead of setting a string using ldapModel.toString(), provide the list itself.
Currently, your LookupResponseResultList class is having a string representation of List. Provide the list instead of string.
I'm not sure how to deserialize array containing plain strings.I'm trying to parse the following JSON
{
"state":"RT",
"testMethod":"electronic",
"testElements":[
{
"testId":[
"UT_ITXref",
"Fed_ITXref"
]
},
"testStartDate",
"testEndDate",
"testDueDate"
]
}
I'm getting the following error:
com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of com.test.rules.model.TestElements: no String-argument constructor/factory method to deserialize from String value ('testStartDate')
at [Source: {"state":"RT","testMethod":"electronic","testElements":[{"testId":["UT_ITXref","Fed_ITXref"]},"testStartDate","testEndDate","testDueDate"}]}; line: 1, column: 247] (through reference chain: com.test.rules.model.TestRules["testElements"]->java.lang.Object[][1])
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:270)
at com.fasterxml.jackson.databind.DeserializationContext.instantiationException(DeserializationContext.java:1456)
at com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1012)
at com.fasterxml.jackson.databind.deser.ValueInstantiator._createFromStringFallbacks(ValueInstantiator.java:370)
at com.fasterxml.jackson.databind.deser.std.StdValueInstantiator.createFromString(StdValueInstantiator.java:315)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromString(BeanDeserializerBase.java:1282)
at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:159)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:150)
at com.fasterxml.jackson.databind.deser.std.ObjectArrayDeserializer.deserialize(ObjectArrayDeserializer.java:196)
at com.fasterxml.jackson.databind.deser.std.ObjectArrayDeserializer.deserialize(ObjectArrayDeserializer.java:20)
at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:499)
at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeWithErrorWrapping(BeanDeserializer.java:511)
at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeUsingPropertyBased(BeanDeserializer.java:396)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(BeanDeserializerBase.java:1198)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:314)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:148)
at com.fasterxml.jackson.databind.ObjectReader._bindAndClose(ObjectReader.java:1626)
at com.fasterxml.jackson.databind.ObjectReader.readValue(ObjectReader.java:1220)
Here is what I did , I used #JsonCreator annotation to deserialize
public class TestRules {
private String state;
private String testMethod;
private TestElements[] testElements;
#JsonCreator
public TaxRules(
#JsonProperty("state") String state,
#JsonProperty("testMethod") String testMethod,
#JsonProperty("testElements") TestElements[] testElements
) {
this.state = state;
this.testMethod = testMethod;
this.testElements = testElements;
}
}
public class TestElements {
private List<String> testId;
private List<String> elements;
public List<String> getElements() {
return elements;
}
public void setElements(List<String> elements) {
this.elements = elements;
}
public List<String> getTestId() {
return testId;
}
public void setTestId(List<String> testId) {
this.testId = testId;
}
}
Should I write custom deserializer or Is there any way that I can use the jackson API for this. Any suggestions would be appreciated.
Actually errors tells something.
JSON parser found that for testElements property there is an Array of Objects, but your Json file has mixed content.
first element is an object (I assume it is TestElement class). Then parser creates that object with empty constructor and calls appropriate setters for its properties.
but...
second,third and forth elements are String, so error says that parser tries to find constrictor with String as argument.
So, you may try to make that constructor in TestElement class and see will it work or not...
Do not forget to keep empty constructor as well.
I cannot guarantee it will work but, at least error says that.
BTW are you sure your Json object is correct? but not something like that?
{
"state":"RT",
"testMethod":"electronic",
"testElements":[
{
"testId":[
"UT_ITXref",
"Fed_ITXref"
]
}],
"testStartDate":"01-01-2017",
"testEndDate":"01-02-2017",
"testDueDate":"01-03-2017"
}
I'm a little confused because StartDate, EndDate, DueDate semantically look more like test attributes, not as elements in testElements array
{
"state": "RT",
"testMethod": "electronic",
"testElements": [
{
"testId": [
"UT_ITXref", // <-- this object is deserialized just fine
"Fed_ITXref"
]
},
"testStartDate", // <-- this is where the error is happening
"testEndDate",
"testDueDate"
]
}
Did you intend the json to be interpreted as if it looked like the following?
{
"state": "RT",
"testMethod": "electronic",
"testElements": [
{
"testId": [
"UT_ITXref",
"Fed_ITXref"
]
},
{
testId: [
"testStartDate"
]
},
{
testId: [
"testEndDate"
]
},
{
testId: [
"testDueDate"
]
}
]
}
If so, you'll need to make a custom deserializer to detect whether the element in the array is an object or a string. If it's a string, you'll probably want to construct the TestElement yourself.
I have a rest application and I'm using Jackson to convert objects to Jsons, but I have a problem:
public class Stats {
public int id;
public String name;
public int stat1;
public float stat2;
}
This method produces a following json:
[[8769,"TEST_PRODUCT#2#0",327,8.0],[8809,"TEST_PRODUCT#4#0",345,9.0],[8749,"TEST_PRODUCT#1#0",349,9.0],[8729,"TEST_PRODUCT#0#0",418,10.0],[8789,"TEST_PRODUCT#3#0",430,11.0]]
But [ and ] is start_array and end_array tokens, and so it is not correct as I think, because my objects are not arrays, so I think something like this would be correct:
[{id: 8769,name:"TEST_PRODUCT#2#0",stat1: 327,stat2: 8.0}, ......]
How can I map my List like this?
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Parsing JSON to Java POJO's using GSON
I'm trying to map this JSON to a POJO with GSON:
{
"get_lists": [
{
"Solution": [
{
"A05": "Herhalingsbezoek vereist"
},
{
"A03": "Melding met oh verholpen"
}
]
},
{
"Problem": [
{
"R07B": "Aandrijving"
},
{
"R07C": "Coating"
}
]
}
]
}
However, both the keys and values inside of the solution and problem can vary, and I haven't had to deal with this before.
If your keys don't vary too much you can make a class having all the desired fields ?
If not you have those solutions :
use a custom Deserializer.
decode as a raw collection : here's an example very similar to your problem.
deserialize your solutions using HashMap<String, String>[] :
public class ListItem {
public HashMap<String, String>[] Solution;
public HashMap<String, String>[] Problem;
}
public class Message {
public ListItem[] get_lists;
}
That's a little heavy but it avoids the use of custom deserializer.
According to me Given Structure represents below POJO
class OuterObject
{
private List<MyObject> getLists;
}
private class MyObject
{
private List<MyKeyValuePair> myList;
}
private class MyKeyValuePair
{
private String key;
private String value;
}
May this help