Deserializing with Jackson - java

I need a way to deserialize this object:
{
"rows": [
{
"id": 0,
"name": "qwe"
}
],
"total": 0
}
to Row[] (i don't need "total") WITHOUT USING OF WAPPER OBJECT:
public class ReviewsWrapper {
private Row[] rows;
#JsonIgnore
private Integer total;
}
directly deserializing it to Rows[]? If there was no "total" object, i would just deserialize using this method:
public static <T> T fromJsonWithRootName(InputStream is, Class<T> type, String rootName) {
try {
return objectMapper.reader(type).withRootName(rootName).readValue(is);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
passing "rows" as a rootName and will get Row[] as output. Is there any way to avoid using WrapperObject for Row[]? It's an Android project I define entities using Jackson Annotations.

Your JSON data Model classes should be like this
package com.example;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"rows",
"total"
})
public class ReviewsWrapper {
#JsonProperty("rows")
private List<Row> rows = new ArrayList<Row>();
#JsonProperty("total")
private long total;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
*
* #return
* The rows
*/
#JsonProperty("rows")
public List<Row> getRows() {
return rows;
}
/**
*
* #param rows
* The rows
*/
#JsonProperty("rows")
public void setRows(List<Row> rows) {
this.rows = rows;
}
public ReviewsWrapper withRows(List<Row> rows) {
this.rows = rows;
return this;
}
/**
*
* #return
* The total
*/
#JsonProperty("total")
public long getTotal() {
return total;
}
/**
*
* #param total
* The total
*/
#JsonProperty("total")
public void setTotal(long total) {
this.total = total;
}
public ReviewsWrapper withTotal(long total) {
this.total = total;
return this;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
public ReviewsWrapper withAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
return this;
}
}
-----------------------------------com.example.Row.java-----------------------------------
package com.example;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"id",
"name"
})
public class Row {
#JsonProperty("id")
private long id;
#JsonProperty("name")
private String name;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
*
* #return
* The id
*/
#JsonProperty("id")
public long getId() {
return id;
}
/**
*
* #param id
* The id
*/
#JsonProperty("id")
public void setId(long id) {
this.id = id;
}
public Row withId(long id) {
this.id = id;
return this;
}
/**
*
* #return
* The name
*/
#JsonProperty("name")
public String getName() {
return name;
}
/**
*
* #param name
* The name
*/
#JsonProperty("name")
public void setName(String name) {
this.name = name;
}
public Row withName(String name) {
this.name = name;
return this;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
public Row withAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
return this;
}
}
Then in Java Class to de-serialize using Jackson use below code
ObjectMapper mapper = new ObjectMapper();
JsonFactory jf = new JsonFactory();
JsonParser jp = jf.createJsonParser("your json data as a String");
ReviewsWrapper reviewWrapper = mapper.readValue(jp,ReviewsWrapper.class);
after this You can get all your response from "ReviewsWrapper.class"
Here is Example using JsonNode try this. is this what you want?
Here is one Example using Nodes.
public class App {
public static class Foo {
public int foo;
}
public static void main(String[] args) {
String json = "{\"someArray\":[{\"foo\":5},{\"foo\":6},{\"foo\":7}]}";
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(json);
node = node.get("someArray");
TypeReference<List<Foo>> typeRef = new TypeReference<List<Foo>>(){};
List<Foo> list = mapper.readValue(node.traverse(), typeRef);
for (Foo f : list) {
System.out.println(f.foo);
} }}

Related

How to get index from an arrayList based on their weightage in java?

I have an ArrayList of transactions for a database in java. Each query has some weight associated with it. I want to execute that transaction that many number of times.
For eg putting 1 transaction in JSON format:-
{
"transaction": {
"name": "NewOrder",
"weight": 45,
"queries": [
{
"query": "select * from account where id > ? and balance > ?",
"bindParams": [
{
"utilityFunction": {
"name": "randomString",
"params": [
{
"minLen": 8,
"maxLen": 16
}
]
}
},
{
"utilityFunction": {
"name": "randomInteger",
"params": [
{
"minValue": 100000,
"maxLen": 100000
}
]
}
}
]
}
I have similar transactions with weights which add upto 100.
I now want to get the id of this transaction from the arraylist of transactions based on its weight.
For eg(transaction names and their weight):-
new order :-45(weight)
stockpurchase:- 30(weight)
newitems :- 15(weight)
deliveryitems :- 10 (weight)
I created an arrayList of integers which stores the sum till that index of transaction :-
[45,75,90,100]
Now I am thinking on invoking a random number[1-100] and get the index that lies closest to it to get the index from the arrayList of transactions.
Is this implementation correct or is there a more efficient way of doing this?
you need to convert your schema to POJO. like this
package com.example;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
public class BindParam {
private UtilityFunction utilityFunction;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
public UtilityFunction getUtilityFunction() {
return utilityFunction;
}
public void setUtilityFunction(UtilityFunction utilityFunction) {
this.utilityFunction = utilityFunction;
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
package com.example;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
public class Param {
private Integer minLen;
private Integer maxLen;
private Integer minValue;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
public Integer getMinLen() {
return minLen;
}
public void setMinLen(Integer minLen) {
this.minLen = minLen;
}
public Integer getMaxLen() {
return maxLen;
}
public void setMaxLen(Integer maxLen) {
this.maxLen = maxLen;
}
public Integer getMinValue() {
return minValue;
}
public void setMinValue(Integer minValue) {
this.minValue = minValue;
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
package com.example;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Generated;
public class Query {
private String query;
private List<BindParam> bindParams = null;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
public String getQuery() {
return query;
}
public void setQuery(String query) {
this.query = query;
}
public List<BindParam> getBindParams() {
return bindParams;
}
public void setBindParams(List<BindParam> bindParams) {
this.bindParams = bindParams;
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
package com.example;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Generated;
#Generated("jsonschema2pojo")
public class Transaction {
private String name;
private Integer weight;
private List<Query> queries = null;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getWeight() {
return weight;
}
public void setWeight(Integer weight) {
this.weight = weight;
}
public List<Query> getQueries() {
return queries;
}
public void setQueries(List<Query> queries) {
this.queries = queries;
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
package com.example;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Generated;
#Generated("jsonschema2pojo")
public class UtilityFunction {
private String name;
private List<Param> params = null;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Param> getParams() {
return params;
}
public void setParams(List<Param> params) {
this.params = params;
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
package com.example;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
public class WrapperClass {
private Transaction transaction;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
public Transaction getTransaction() {
return transaction;
}
public void setTransaction(Transaction transaction) {
this.transaction = transaction;
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
public class Main() {
public static void main(String[] args) {
//assume that you collect data from getValue()
List<WrapperClass> wrappers = getValue();
for(WrapperClass wrapper : wrappers) {
Transaction transaction = wrapper.getTransaction();
int weight = transaction.getWeight();
}
}
}
you can use JSONSchema2POJO to generate model from json.

How can I convert a map to an object?

I made a Map to store the values of all tags on a SOAPMessage body, so that the keys of the Map are the node names and the values are the text contents. I have an object where I already have the fields named after the node names, what I need to do is to set their values accordingly to their map counterparts.
Say that I have a node named "Summary" on the SOAPMessage, there will be a Map key named "Summary" and also an object field named "Summary". I need the object field "Summary" to be set as the value of the Map.get("Summary").
I know I could just fill my code with setters for each of the fields, but is there an way to set the entire object from the Map?
This is the method where I created the Map.
private static Map<String, String> mapIncidentInfo(SOAPMessage soapResponse) throws SOAPException {
Map<String, String> fields = new HashMap<String, String>();
NodeList nodes = soapResponse.getSOAPBody().getFirstChild().getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
fields.put(node.getNodeName(), node.getTextContent());
}
return fields;
}
This could be used as an object class example:
public class IncidentPO {
private String Submitter;
private String Submit_Date;
private String Last_Modified_By;
private String Last_Modified_Date;
private String Status;
private String Short_Description;
public IncidentPO(String Submitter, String Submit_Date, String Last_Modified_By, String Last_Modified_Date, String Status, String Short_Description) {
this.Submitter = Submitter;
this.Submit_Date = Submit_Date;
this.Last_Modified_By = Last_Modified_By;
this.Last_Modified_Date = Last_Modified_Date;
this.Status = Status;
this.Short_Description = Short_Description;
//getters and setters here
There's no easy way (without libraries) to convert a Map to object. A direct option is to provide the Map in a constructor and have it populate itself.
public IncidentPO(Map<String, String> map) {
this.Submitter = map.get("Submitter");
this.Submit_Date = map.get("Submit_Date");
// etc
}
You can use object to json mapping then again json to object as below:
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
public class TestMap {
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
Map<String, String> myMmap = new HashMap<>();
myMmap.put("name", "ABC");
myMmap.put("age", "20");
myMmap.put("sex", "male");
myMmap.put("city", "madhepura");
myMmap.put("spec", "java");
ObjectMapper mapper = new ObjectMapper();
ObjectNode objectNode1 = mapper.createObjectNode();
for(String key : myMmap.keySet()) {
objectNode1.put(key, myMmap.get(key));
}
// take the value of objectNode1.toString() and create a pojo from http://www.jsonschema2pojo.org/
Person person = mapper.readValue(objectNode1.toString().getBytes(), Person.class);
System.out.println(person);
}
}
// you can use http://www.jsonschema2pojo.org to get POJO from objectNode1.toString()
// {"city":"patna","sex":"male","name":"ABC","age":"20","spec":"java"}
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"city",
"sex",
"name",
"age",
"spec"
})
class Person {
#JsonProperty("city")
private String city;
#JsonProperty("sex")
private String sex;
#JsonProperty("name")
private String name;
#JsonProperty("age")
private String age;
#JsonProperty("spec")
private String spec;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("city")
public String getCity() {
return city;
}
#JsonProperty("city")
public void setCity(String city) {
this.city = city;
}
#JsonProperty("sex")
public String getSex() {
return sex;
}
#JsonProperty("sex")
public void setSex(String sex) {
this.sex = sex;
}
#JsonProperty("name")
public String getName() {
return name;
}
#JsonProperty("name")
public void setName(String name) {
this.name = name;
}
#JsonProperty("age")
public String getAge() {
return age;
}
#JsonProperty("age")
public void setAge(String age) {
this.age = age;
}
#JsonProperty("spec")
public String getSpec() {
return spec;
}
#JsonProperty("spec")
public void setSpec(String spec) {
this.spec = spec;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}

TreeView of objects having child nodes that are fields of the object

I have an object with fields of varying datatypes:
public class MyObject{
private String field1;
private CustomObject field2;
private int field3;
...
}
I want to create a tree view of MyObject that will have multiple MyObject nodes, each with the fields (field1, field2, field3..etc) as children.
I know I can make a TreeView of Strings and populate it myself with an addNode(MyObject obj) method in which I would add the individual TreeItems I need. However, I did this with a TableView where I was able to bind a column with a field property. Such as:
TableView<MyObject> table;
TableColumn<MyObject, String> myColumn;
myColumn.setCellValueFactory(new PropertyValueFactory<>("field1"));
Is there any way to do something similar for a TreeView<MyObject>? Im not opposed to creating a subclass that extends TreeItem<?>
The ending result I'm looking for would be something like this:
--> First My Object
->field1: "Value at Field 1"
->field2: "Value at Field 2"
->field3: 3
--> Second My Object
->field1: "Value at Field 1"
->field2: "Value at Field 2"
->field3: 3
Pretty much any time you use a TreeView with different types in different nodes of the tree, you will need some casting and/or type checking somewhere.
One possible approach here is to subclass TreeItem to provide a field for the property you want to show, and then to use a TreeCell that shows the string value of that property.
Here's a very basic example of that:
import java.util.Arrays;
import java.util.List;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TreeCell;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.stage.Stage;
public class TreeViewWithProperties extends Application {
#Override
public void start(Stage primaryStage) {
List<SomeEntity> entities = Arrays.asList(
new SomeEntity("First object", "String value 1", 42),
new SomeEntity("Second object", "String value 2", 3)
);
TreeView<SomeEntity> tree = new TreeView<>();
tree.setShowRoot(false);
TreeItem<SomeEntity> treeRoot = new TreeItem<>();
tree.setRoot(treeRoot);
for (SomeEntity entity : entities) {
TreeItem<SomeEntity> item = PropertyTreeItem.baseItem(entity);
treeRoot.getChildren().add(item);
item.getChildren().add(new PropertyTreeItem<String>(entity, entity.getStringField()));
item.getChildren().add(new PropertyTreeItem<Integer>(entity, entity.getValue()));
}
tree.setCellFactory(tv -> new TreeCell<SomeEntity>() {
#Override
protected void updateItem(SomeEntity entity, boolean empty) {
super.updateItem(entity, empty);
PropertyTreeItem<?> item = (PropertyTreeItem<?>) getTreeItem();
if (empty) {
setText(null);
} else {
setText(item.getPropertyValue().toString());
}
}
});
Scene scene = new Scene(tree);
primaryStage.setScene(scene);
primaryStage.show();
}
public static class PropertyTreeItem<T> extends TreeItem<SomeEntity> {
private final T propertyValue ;
public PropertyTreeItem(SomeEntity entity, T value) {
super(entity);
this.propertyValue = value ;
}
public static PropertyTreeItem<SomeEntity> baseItem(SomeEntity entity) {
return new PropertyTreeItem<>(entity, entity);
}
public T getPropertyValue() {
return propertyValue ;
}
}
public class SomeEntity {
private String name ;
private String stringField ;
private int value ;
public SomeEntity(String name, String stringField, int value) {
this.name = name;
this.stringField = stringField;
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStringField() {
return stringField;
}
public void setStringField(String stringField) {
this.stringField = stringField;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
#Override
public String toString() {
return name ;
}
}
public static void main(String[] args) {
launch(args);
}
}
Some variations on this are possible, of course. If you wanted to use JavaFX properties in the entity class, and be able to change those values externally to the tree, you could bind the text to the property in the cell instead of simply setting it.
Using some ideas from the link I posted under your question. This example uses a helper Class to create the TreeItems.
Main
import java.util.ArrayList;
import java.util.List;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
/**
*
* #author blj0011
*/
public class JavaFXApplication128 extends Application
{
#Override
public void start(Stage primaryStage)
{
MyObject myObject1 = new MyObject("myObject1", "field 1 a", new CustomObject("customObject 1", 3), 5);
MyObject myObject2 = new MyObject("myObject2", "field 1 b", new CustomObject("customObject 2", 36), 10);
MyObject myObject3 = new MyObject("myObject3", "field 1 c", new CustomObject("customObject 3", 23), 8);
List<MyObject> list = new ArrayList();
list.add(myObject1);
list.add(myObject2);
list.add(myObject3);
List<TreeItem<String>> treeItemsContainer = new ArrayList();
for (MyObject object : list) {
ObjectToTreeView objectToTreeView = new ObjectToTreeView(object);
treeItemsContainer.add(objectToTreeView.getRootItem());
}
TreeItem<String> rootItem = new TreeItem();
rootItem.setExpanded(true);
rootItem.getChildren().addAll(treeItemsContainer);
TreeView treeView = new TreeView(rootItem);
Scene scene = new Scene(treeView, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
launch(args);
}
}
ObjectToTreeView Class <- a helper class
import javafx.scene.control.TreeItem;
/**
*
* #author blj0011
*/
public class ObjectToTreeView
{
private final TreeItem<String> rootItem = new TreeItem();
public ObjectToTreeView(MyObject myObject)
{
rootItem.setValue(myObject.getTitle());
rootItem.getChildren().add(new TreeItem(myObject.getField1()));
CustomObject customObject = myObject.getField2();
rootItem.getChildren().add(new TreeItem(customObject.getName()));
rootItem.getChildren().add(new TreeItem(customObject.getNumber()));
rootItem.getChildren().add(new TreeItem(myObject.getField3()));
}
/**
* #return the rootItem
*/
public TreeItem<String> getRootItem()
{
return rootItem;
}
}
MyObject Class
/**
*
* #author blj0011
*/
public class MyObject
{
private String title;
private String field1;
private CustomObject field2;
private int field3;
public MyObject(String title, String field1, CustomObject field2, int field3)
{
this.title = title;
this.field1 = field1;
this.field2 = field2;
this.field3 = field3;
}
/**
* #return the title
*/
public String getTitle()
{
return title;
}
/**
* #param title the title to set
*/
public void setTitle(String title)
{
this.title = title;
}
/**
* #return the field1
*/
public String getField1()
{
return field1;
}
/**
* #param field1 the field1 to set
*/
public void setField1(String field1)
{
this.field1 = field1;
}
/**
* #return the field3
*/
public int getField3()
{
return field3;
}
/**
* #param field3 the field3 to set
*/
public void setField3(int field3)
{
this.field3 = field3;
}
/**
* #return the field2
*/
public CustomObject getField2()
{
return field2;
}
/**
* #param field2 the field2 to set
*/
public void setField2(CustomObject field2)
{
this.field2 = field2;
}
}
CustomObject Class
/**
*
* #author blj0011
*/
public class CustomObject
{
private String name;
private int number;
public CustomObject(String name, int number)
{
this.name = name;
this.number = number;
}
/**
* #return the name
*/
public String getName()
{
return name;
}
/**
* #param name the name to set
*/
public void setName(String name)
{
this.name = name;
}
/**
* #return the number
*/
public int getNumber()
{
return number;
}
/**
* #param number the number to set
*/
public void setNumber(int number)
{
this.number = number;
}
}
I ended up just creating a helper function by doing the following:
public TreeItem<String> createNode(MyObject obj) {
TreeItem<String> node = null;
if(obj != null) {
node = new TreeItem<String>("MyObject:" + obj.getId());
node.getChildren().add(new TreeItem<String>("Field1: "+ obj.getField1()));
node.getChildren().add(new TreeItem<String>("Field2: "+ obj.getField2()));
node.getChildren().add(new TreeItem<String>("Field3: "+ obj.getField3()));
}
}

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "g"

Could some one please whats wrong with the below java pojo. I an getting exception
Json
{
"epoch": 1407877412466,
"ids": {
"DUMMY1": "abcd",
"DUMMY2": "pqrs"
},
"vf": {
"ANS1": {
"g": 0
},
"ANS2": {
"g": 0
},[...]
}
}
Exception
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "g" (class com.adtruth.zander.persistence.domain.VfdData), not marked as ignorable (4 known properties: "query", "vf", "ids", "epoch"])
at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:51)
at com.fasterxml.jackson.databind.DeserializationContext.reportUnknownProperty(DeserializationContext.java:731)
at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:915)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1298)
POJO
package com.temp;
import java.io.IOException;
import java.io.Serializable;
import java.util.Calendar;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.Maps;
#JsonInclude(Include.NON_EMPTY)
public class VfdData implements Serializable {
#JsonProperty("epoch")
private Long epoch = Calendar.getInstance().getTimeInMillis();
#JsonProperty("query")
private boolean query = false;
#JsonProperty("ids")
private Map<String, Object> ids = Maps.newHashMap();
#JsonProperty("vf")
private Map<String, Scores> vfScores = Maps.newLinkedHashMap();
public Long getEpoch() {
return epoch;
}
public void setEpoch(final Long epoch) {
this.epoch = epoch;
}
public boolean isQuery() {
return query;
}
public void setQuery(final boolean query) {
this.query = query;
}
public Map<String, Object> getIds() {
return ids;
}
public void setIds(final Map<String, Object> ids) {
this.ids = ids;
}
public Map<String, Scores> getVfScores() {
return vfScores;
}
public void setVfScores(final Map<String, Scores> vfScores) {
this.vfScores = vfScores;
}
#JsonInclude(Include.NON_EMPTY)
public class Scores {
#JsonCreator
public Scores() {
}
#JsonProperty("g")
private Integer score;
public Integer getScore() {
return score;
}
public void setScore(final Integer score) {
this.score = score;
}
}
}
The Scores class should be static (or be a top-level class).

Converting JSON object to string in JAXB

Am writing an Webservice endpoint which will produce JSON and XML response. Here i would like to convert an object to JSON and setting it to string. When i try to do with the below code
Webservice Endpoint
package com.test1;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;`
#Path("v1")
public class Impl1 {
#POST
#Path("method")
#Produces({"text/xml","application/json"})
public XML method() throws JSONException
{
//JSONObject obj = new JSONObject();
JSONArray ary = new JSONArray();
Main main = new Main();`
List<Student> details = new ArrayList<Student>() ;
Student s1 = new Student();
Student s2 = new Student();
Student s3 = new Student();
s1.setId("ID1");
s1.setValue("1");
s2.setId("ID2");
s2.setValue("2");
s3.setId("ID3");
s3.setValue("3");
details.add(s1);
details.add(s2);
details.add(s3);
main.setDetails(details);
ary.put(details);
Employee emp = new Employee();
emp.setName("Mike");
emp.setSalary(1000);
XML xml = new XML();
xml.setDetails(ary.toString());
xml.setEmp(emp);
xml.setId("1");
return xml;
}
}
XML class (JAXB)
package com.test1;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class XML {
String id;
Employee emp;
String details;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Employee getEmp() {
return emp;
}
public void setEmp(Employee emp) {
this.emp = emp;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
}
Student Class
package com.test1;
public class Student {
String id;
String Value;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getValue() {
return Value;
}
public void setValue(String value) {
Value = value;
Main Class
package com.test1;
import java.util.List;
public class Main {
List<Student> details;
public List<Student> getDetails() {
return details;
}
public void setDetails(List<Student> details) {
this.details = details;
}
}
So when i hit my service am getting response as
{
"details" : "[[{\"id\":\"ID1\",\"value\":\"1\"},{\"id\":\"ID2\",\"value\":\"2\"},{\"id\":\"ID3\",\"value\":\"3\"}]]",
"emp" : {
"name" : "Arun",
"salary" : "1000.0"
},
"id" : "1"
}
Expected String valuse as
[{"id":"ID1","value":"1"},{"id":"ID2","value":"2"},{"id":"ID3","value":"3"}]
My Question is Why JSONArray which was converted as String contains "\" on every key value pair. is there any way to overcome this?
Use Jackson or google-gson or any other library.
For example
http://howtodoinjava.com/2014/06/16/jackson-examples-convert-java-object-to-from-json/

Categories

Resources