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

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).

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.

Empty List in Drools rule

I ran into a problem in a rule called "Due date for test1". I pass the list called "tests" as a parameter to
check it for Test.Test1, but the list is empty, despite the fact that before that I filled it in the rule "test for type1". What is the problem?
here is code of entity "Machine":
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Machine {
private String type;
public ArrayList<Test> tests= new ArrayList<Test>();
private List<String> functions = new ArrayList<String>();
private Date creationTime =null;
private Date testTime = null;
public Machine (String type) {
this.type= type;
}
public void setType(String type) {
this.type= type;
}
public String getType() {
return type;
}
public void setTests(ArrayList<Test> tests) {
this.tests = tests;
}
public void setFunctions(List<String> functions) {
this.functions = functions;
}
public List<String> functions() {
return functions;
}
public List<Test> getTests() {
return tests;
}
public void setCreationTime(Date creationTime) {
this.creationTime = creationTime;
}
public Date getCreationTime() {
return creationTime;
}
public void setTestTime(Date testTime) {
this.testTime = testTime;
}
public Date getTestTime() {
return testTime;
}
}
here is code of entity "Test":
package com.sample;
import java.util.Calendar;
public enum Test {
Test1(1),Test2(2),Test3(3);
private Integer id;
Test(Integer id) {
this.id=id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setTestsDueTime(Machine m,int numOfDays) {
setTest(m,Calendar.DAY_OF_YEAR,numOfDays);
}
public void setTest(Machine m,int calendarType,int numOfDays) {
Calendar c = Calendar.getInstance();
c.setTime(m.getCreationTime());
c.add(calendarType, numOfDays);
m.setTestTime(c.getTime());
}
}
here is drl code:
package com.sample
import com.sample.Machine;
import com.sample.Test;
rule "test for type1"
when
m : Machine(type == "type1");
then
Test t1=Test.Test1;
Test t2 = Test.Test2;
Test t3 = Test.Test3;
m.getTests().add(t1);
m.getTests().add(t2);
m.getTests().add(t3);
insert(m);
insert(m);
insert(m) ;
end
rule "Due date for test1"
when
m:Machine(type == "type1", tests contains Test.Test1);
then
System.out.print("условие прошло");
//t.setTestsDueTime( m,3);
end
main class code:
package com.sample;
import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
public class DroolsTest {
public static final void main(String[] args) {
try {
// load up the knowledge base
KieServices ks = KieServices.Factory.get();
KieContainer kContainer = ks.getKieClasspathContainer();
KieSession kSession = kContainer.newKieSession("ksession-rules");
// go !
Machine m = new Machine("type1");
kSession.insert(m);
kSession.fireAllRules();
} catch (Throwable t) {
t.printStackTrace();
}
}
}
insert(m);
insert(m);
insert(m);
This doesn't make any sense. m is already in Working Memory.
What you need is one
update(m);
instead.

Deserializing with Jackson

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);
} }}

Simple json structure throwing error when converting to pojo

I am attempting to convert a json String to a java pojo but receive this error when parsing :
org.codehaus.jackson.map.JsonMappingException: Can not instantiate value of type [simple type, class com.json.pojo.Userdatum] from JSON String; no single-String constructor/factory method
at org.codehaus.jackson.map.deser.std.StdValueInstantiator._createFromStringFallbacks(StdValueInstantiator.java:379)
at org.codehaus.jackson.map.deser.std.StdValueInstantiator.createFromString(StdValueInstantiator.java:268)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromString(BeanDeserializer.java:765)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:585)
at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2732)
at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1863)
at com.json.pojo.ParseJson.main(ParseJson.java:21)
here is my conversion code :
package com.json.pojo;
import java.io.IOException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
import org.codehaus.jackson.annotate.JsonMethod;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
public class ParseJson {
public static void main(String args[]){
String str = "\"userdata\": [ {\"userid\": \"user1\",\"title\": \"Next weeks preview\", \"date\": \"19/12/2013\",\"time\": \"15:00\"}";
org.codehaus.jackson.map.ObjectMapper mapper = new org.codehaus.jackson.map.ObjectMapper();
mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
try {
com.json.pojo.Userdatum user = mapper.readValue(str, com.json.pojo.Userdatum.class);
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And my pojo :
package com.json.pojo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#Generated("com.googlecode.jsonschema2pojo")
#JsonPropertyOrder({
"userdata"
})
public class UserData {
#JsonProperty("userdata")
private List<Userdatum> userdata = new ArrayList<Userdatum>();
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("userdata")
public List<Userdatum> getUserdata() {
return userdata;
}
#JsonProperty("userdata")
public void setUserdata(List<Userdatum> userdata) {
this.userdata = userdata;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperties(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
package com.json.pojo;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#Generated("com.googlecode.jsonschema2pojo")
#JsonPropertyOrder({
"userid",
"title",
"date",
"time"
})
public class Userdatum {
#JsonProperty("userid")
private String userid;
#JsonProperty("title")
private String title;
#JsonProperty("date")
private String date;
#JsonProperty("time")
private String time;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("userid")
public String getUserid() {
return userid;
}
#JsonProperty("userid")
public void setUserid(String userid) {
this.userid = userid;
}
#JsonProperty("title")
public String getTitle() {
return title;
}
#JsonProperty("title")
public void setTitle(String title) {
this.title = title;
}
#JsonProperty("date")
public String getDate() {
return date;
}
#JsonProperty("date")
public void setDate(String date) {
this.date = date;
}
#JsonProperty("time")
public String getTime() {
return time;
}
#JsonProperty("time")
public void setTime(String time) {
this.time = time;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperties(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
There must be something wrong with the generated pojo but it looks correct ?
This works, for some reason I needed to use the #JsonProperty even though my properties are matching the json attributes, I did'nt think they were required.
package com.json.pojo;
import java.io.IOException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
import org.codehaus.jackson.annotate.JsonMethod;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
public class ParseJson {
public static void main(String args[]){
String str = "{ \"userdata\": [ {\"userid\": \"user1\",\"title\": \"Next weeks preview\", \"date\": \"19/12/2013\",\"time\": \"15:00\"} ] }";
org.codehaus.jackson.map.ObjectMapper mapper = new org.codehaus.jackson.map.ObjectMapper();
mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, true);
try {
com.json.pojo.RequestBean user = mapper.readValue(str, com.json.pojo.RequestBean.class);
System.out.println(user.getToAdd().size());
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package com.json.pojo;
import java.io.Serializable;
import java.util.List;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.annotate.JsonSerialize;
#JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
#JsonIgnoreProperties(ignoreUnknown = true)
public class RequestBean implements Serializable {
#JsonProperty("userdata")
private List<SimpleBean> userdata;
public List<SimpleBean> getToAdd() {
return userdata;
}
public void setToAdd(List<SimpleBean> toAdd) {
this.userdata = toAdd;
}
// constructors, getters, setters
}
package com.json.pojo;
import java.io.Serializable;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.annotate.JsonSerialize;
#JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
#JsonIgnoreProperties(ignoreUnknown = true)
public class SimpleBean implements Serializable {
#JsonProperty("userid")
private String userid;
#JsonProperty("title")
private String title;
#JsonProperty("date")
private String date;
#JsonProperty("time")
private String time;
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}

How to escape from ClassCastException

This is my collection:
db.power.find().pretty()
{
"_id" : ObjectId("513e4022cc6d8d7ff2c83239"),
"Indicator" : "One",
"sex" : "male"
}
How to escape from ClassCastException?
import java.net.UnknownHostException;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;
public class Test {
public static void main(String args[]) throws UnknownHostException {
Mongo mongo = new Mongo();
DB db = mongo.getDB("at");
DBCollection testdata = db.getCollection("power");
BasicDBObject query = new BasicDBObject();
query.put("Indicator", "One");
PowerData data = (PowerData) testdata.findOne(query);
System.out.println(data.getSize());
}
}
import com.mongodb.BasicDBObject;
public class PowerData extends BasicDBObject{
public String getSize() {
return (String) get("sex");
}
public void setSize(String sex) {
put("sex", sex);
}
public String getIndicator() {
return (String) get("Indicator");
}
public void setIndicator(String Indicator) {
put("Indicator", Indicator);
}
public String getId() {
return (String) get("_id");
}
public void setId(String _id) {
put("_id", _id);
}
}
Exception in thread "main" java.lang.ClassCastException: com.mongodb.BasicDBObject cannot be cast to PowerData
at Test.main(Test.java:19)
You could change your PowerData class like this:
public class PowerData extends BasicDBObject{
private BasicDBObject wrapped;
public PowerData(BasicDBObject o) {
this.wrapped = o;
}
public String getSize() {
return (String) o.get("sex");
}
public void setSize(String sex) {
o.put("sex", sex);
}
public String getIndicator() {
return (String) o.get("Indicator");
}
public void setIndicator(String Indicator) {
o.put("Indicator", Indicator);
}
public String getId() {
return (String) o.get("_id");
}
public void setId(String _id) {
o.put("_id", _id);
}
}
And in your main method, replace PowerData data = (PowerData) testdata.findOne(query); with following:
PowerData data = new PowerData(testdata.findOne(query));

Categories

Resources