Parsing JSON Object within an Object java - java

Am trying to map this json with volley. But I keep getting an error inside my constructor each time.
[
{
"id": 19,
"time_created": {
"date": "2018-09-18 09:24:34.000000",
"timezone_type": 3,
"timezone": "America/Chicago"
},
]
So I need to fetch the time_created object. This is my model class;
public class NeighbourhoodOther implements Serializable{
public int id;
public TimeCreated timeCreated;
public NeighbourhoodOther(){
}
public NeighbourhoodOther(int id, TimeCreated timeCreated ) {
this.id = id;
this.timeCreated= time_created;
}
public TimeCreated getTimeCreated() {
return timeCreated;
}
public void setTimeCreated(TimeCreated timeCreated) {
this.timeCreated = timeCreated;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public static class TimeCreated {
public String timezone;
public int timezoneType;
public String date;
public String getTimezone() {
return timezone;
}
public void setTimezone(String timezone) {
this.timezone = timezone;
}
public int getTimezoneType() {
return timezoneType;
}
public void setTimezoneType(int timezoneType) {
this.timezoneType = timezoneType;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
}
This is the way am trying to fetch with volley but I get an error each time.
for (int i = 0; i < neighOther.length(); i++) {
JSONObject neighOtherObject = neighOther.getJSONObject(i);
int id = neighOtherObject.getInt("id");
NeighbourhoodOther.TimeCreated timeCreated = neighOtherObject.getJSONObject("time_created");
NeighbourhoodOther neighbourhoodOther = new NeighbourhoodOther(id, time_created);
otherNeighbourHoodList.add(neighbourhoodOther);
}
The error inside my constructor says its expecting a JSONObject instead of TimeCreated. Whats the best way to fetch the data. I need to pass the date String to a TextView.

NeighbourhoodOther.TimeCreated timeCreated = neighOtherObject.getJSONObject("time_created") returns a JSONObject not NeighbourhoodOther.TimeCreated
try:
JSONObject obj = neighOtherObject.getJSONObject("time_created");
NeighbourhoodOther.TimeCreated temp = new NeighbourhoodOther.TimeCreated()
temp.timezone = obj.getString("timezone");
... fill in NeighbourhoodOther.TimeCreated members

getJSONObject return a jsonobject, so you should cast it to custom type.
There are lots of libray to do this, Gson is the one.
import com.google.gson.Gson;
//other stuffs
Gson gson= new Gson();
TimeCreated obj = gson.fromJson(neighOtherObject.getJSONObject("time_created").toString(), TimeCreated.class);

Related

Can not store list of objects as single column JSON

I'm trying to store a whole array of object into one field on my oracle database, I'm referring to the solution on this question, but it kept giving me Can not set java.lang.String field xxx.demo.Models.Sensors.amplitudos to xxx.demo.Models.Sensors error, I have checked the JSON body and the entity class, but I cannot find the mistake.
Here is my code.
entity
#Entity
#Table(name = "SENSOR")
public class Sensor implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name = "TIMERECEIVED")
private Timestamp timereceived;
#Column(name = "SENSORS")
private Sensors[] sensors;
#Column(name = "LOC")
private String location;
public Sensor() {
}
public Sensor(Timestamp timereceived, Sensors[] sensors, String location) {
this.timereceived = timereceived;
this.sensors = sensors;
this.location = location;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Timestamp getTimereceived() {
return timereceived;
}
public void setTimereceived(Timestamp timereceived) {
this.timereceived = timereceived;
}
public Sensors[] getSensors() {
return sensors;
}
public void setSensors(Sensors[] sensors) {
this.sensors = sensors;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
Sensors class
#Embeddable
public class Sensors {
private String amplitudos;
private Double displacement;
private String frequencies;
private Integer sensorId;
public Sensors() {
}
public Sensors(String amplitudos, Double displacement, String frequencies, Integer sensorId) {
this.amplitudos = amplitudos;
this.displacement = displacement;
this.frequencies = frequencies;
this.sensorId = sensorId;
}
public String getAmplitudos() {
return amplitudos;
}
public void setAmplitudos(String amplitudos) {
this.amplitudos = amplitudos;
}
public Double getDisplacement() {
return displacement;
}
public void setDisplacement(Double displacement) {
this.displacement = displacement;
}
public String getFrequencies() {
return frequencies;
}
public void setFrequencies(String frequencies) {
this.frequencies = frequencies;
}
public Integer getSensorId() {
return sensorId;
}
public void setSensorId(Integer sensorId) {
this.sensorId = sensorId;
}
}
my JSON body
{
"timereceived": "2022-11-29T12:04:42.166",
"sensors": [
{
"amplitudos": "a1#a2#a3#a4",
"displacement": 0.002,
"frequencies": "f1#f2#f3#f4",
"sensorid": 1
},
{
"amplitudos": "a1#a2#a3#a4",
"displacement": 0.002,
"frequencies": "f1#f2#f3#f4",
"sensorid": 2
},
{
"amplitudos": "a1#a2#a3#a4",
"displacement": 0.002,
"frequencies": "f1#f2#f3#f4",
"sensorid": 3
},
{
"amplitudos": "a1#a2#a3#a4",
"displacement": 0.002,
"frequencies": "f1#f2#f3#f4",
"sensorid": 4
}
],
"location": "lokasi"
}
my controller
#PostMapping("/sendData")
public ResponseEntity sendData(#RequestBody Sensor sensor) {
Sensor newSensor = sensorRepository.save(sensor);
System.out.println(newSensor);
return ResponseEntity.ok("Sensor received");
}
I have tried checking every possible solution and the problem is not fixed, my expectation is the data stored into 1 column for the sensors field in the JSON body.
The problem is with the JPA mapping, not with the Controller, I think.
You're using #Embeddable, which normally result in a set of columns in your main table. If it's a collection of #Embeddable objects, you could map it to a separate table with foreign keys, using #ElementCollection.
However, you want to store the collection of sensors as a single JSON string in a single column in your main table. For that, you do not need the #Embeddable annotation. You need to write a custom convertor to convert the collection of sensors to JSON.
public class SensorsConverter implements AttributeConverter<List<Sensors>, String> {
private final ObjectMapper objectMapper = new ObjectMapper();
#Override
public String convertToDatabaseColumn(List<Sensors> sensors) {
return objectMapper.writeValueAsString(sensors);
}
#Override
public List<Sensors> convertToEntityAttribute(String sensorsJSON) {
return objectMapper.readValue(sensorsJSON, new TypeReference<List<Sensors>>() {});
}
}
Then you can use it in your entity class:
#Column(name = "SENSORS")
#Convert(converter = SensorsConverter.class)
private List<Sensors> sensors;

How to parse json file to java using boon and rest?

I'm trying to parse a JSON file which I get via API to pojo. After searching on internet I see boon is working with rest but I can't figure out how.
According to this article it should work but....
In my code HTTP.getJSON() method require a map as parameter which I can't figure out what exactly this map is.
Any genius one can give a working example of boon?
public class ViewTimeline{
public void view() {
ObjectMapper mapper = JsonFactory.create();
List<String> read = IO.readLines("https://corona-api.com/timeline");
Map<String, ?> headers = null ;
List<Timeline> timelineList = mapper.readValue(HTTP.getJSON("https://corona-api.com/timeline", headers), List.class, Timeline.class);
}
}
TimeLine.java
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"updated_at",
"date",
"deaths",
"confirmed",
"recovered",
"active",
"new_confirmed",
"new_recovered",
"new_deaths",
"is_in_progress"
})
public class Timeline {
#JsonProperty("updated_at")
private String updatedAt;
#JsonProperty("date")
private String date;
#JsonProperty("deaths")
private Integer deaths;
#JsonProperty("confirmed")
private Integer confirmed;
#JsonProperty("recovered")
private Integer recovered;
#JsonProperty("active")
private Integer active;
#JsonProperty("new_confirmed")
private Integer newConfirmed;
#JsonProperty("new_recovered")
private Integer newRecovered;
#JsonProperty("new_deaths")
private Integer newDeaths;
#JsonProperty("is_in_progress")
private Boolean isInProgress;
#JsonProperty("updated_at")
public String getUpdatedAt() {
return updatedAt;
}
#JsonProperty("updated_at")
public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}
#JsonProperty("date")
public String getDate() {
return date;
}
#JsonProperty("date")
public void setDate(String date) {
this.date = date;
}
#JsonProperty("deaths")
public Integer getDeaths() {
return deaths;
}
#JsonProperty("deaths")
public void setDeaths(Integer deaths) {
this.deaths = deaths;
}
#JsonProperty("confirmed")
public Integer getConfirmed() {
return confirmed;
}
#JsonProperty("confirmed")
public void setConfirmed(Integer confirmed) {
this.confirmed = confirmed;
}
#JsonProperty("recovered")
public Integer getRecovered() {
return recovered;
}
#JsonProperty("recovered")
public void setRecovered(Integer recovered) {
this.recovered = recovered;
}
#JsonProperty("active")
public Integer getActive() {
return active;
}
#JsonProperty("active")
public void setActive(Integer active) {
this.active = active;
}
#JsonProperty("new_confirmed")
public Integer getNewConfirmed() {
return newConfirmed;
}
#JsonProperty("new_confirmed")
public void setNewConfirmed(Integer newConfirmed) {
this.newConfirmed = newConfirmed;
}
#JsonProperty("new_recovered")
public Integer getNewRecovered() {
return newRecovered;
}
#JsonProperty("new_recovered")
public void setNewRecovered(Integer newRecovered) {
this.newRecovered = newRecovered;
}
#JsonProperty("new_deaths")
public Integer getNewDeaths() {
return newDeaths;
}
#JsonProperty("new_deaths")
public void setNewDeaths(Integer newDeaths) {
this.newDeaths = newDeaths;
}
#JsonProperty("is_in_progress")
public Boolean getIsInProgress() {
return isInProgress;
}
#JsonProperty("is_in_progress")
public void setIsInProgress(Boolean isInProgress) {
this.isInProgress = isInProgress;
}
}
To parse an json to an object, I used Jackson. I also saw you used Jackson at mapping in Timeline.
Jackson Core: https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core/2.11.0
Jackson Databind: https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind/2.11.0
Jackson Annotation: https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations/2.11.0
This is the way I handled it:
public static void main(String[] args) throws JsonProcessingException {
//my method to read content from website.
//using apache http
String jsonApi = getApi();
ObjectMapper objectMapper = new ObjectMapper();
//todo JsonProcessingException
JsonNode data = objectMapper.readTree(jsonApi);
//get data field from data, which is an array
//todo This can throws error if data field is missing
JsonNode dataArray = data.get("data");
List<Timeline> timelineList = new ArrayList<>();
if(dataArray.isArray()){
for(JsonNode line : dataArray){
//todo this can throws errors. need to handle it.
Timeline timeline = objectMapper.readValue(line.toString(), Timeline.class);
timelineList.add(timeline);
}
}else{
System.out.println("JsonApi is not array: '" + jsonApi + "'");
}
System.out.println("Size: " + timelineList.size());
for(Timeline timeline : timelineList){
System.out.println(timeline.getConfirmed());
}
}
At this code you should handle the exceptions. I marked them by comments.

Ljava.lang.Object; cannot be cast to model

in this case, i want to show Json to an response page in java hibernate, query method from DAO like this:
public List<TransactionQR> getAllTransaction() throws HibernateException {
return this.session.createQuery("FROM TransactionQR tr, Batch b, Terminal t, User_Smartphone us, Merchant mc WHERE tr.batch = b.id AND b.user_smartphone = us.id AND b.terminal = t.id AND t.merchant = mc.id AND state = '1' ").list();
}
then in servlet class i try to convert the list into json using Json object and json array then write in response like this:
int start = 0;
String jsonResult = null;
JSONObject jo=new JSONObject();
HttpServletRequest request = context.getRequest();
HttpServletResponse response = context.getResponse();
HttpSession session = context.getSession();
DB db = getDB(context);
//JSONObject jo = new JSONObject();
QRTransactionDao QR = new QRTransactionDao(db);
//Gson objGson = new GsonBuilder().setPrettyPrinting().create();
//String json = objGson.toJson(QR.getAllTransaction());
//System.out.println(json);
List<TransactionQR> str = QR.getAllTransaction();
JSONArray array = new JSONArray();
for(TransactionQR tr : str){
JSONObject str3 = new JSONObject();
str3.put("amount", tr.getAmount());
context.put("jsoncontent", jsonResult);
array.add(str3);
}
jo.put("status", "ok");
jo.put("dataqr", array);
jsonResult=jo.toString();
response.setContentType("application/json");
response.getWriter().print(jsonResult);
but i got the error on syntax in this line loop:
for(TransactionQR tr : str){
the error like this:
[Ljava.lang.Object; cannot be cast to Transaction
here the model Transaction:
package id.co.keriss.consolidate.ee;
import java.io.Serializable;
import java.util.Date;
public class TransactionQR implements Serializable{
private Long id;
private String codeqr;
private Date approvaltime;
private String merchant;
private String code_merchant;
private Long amount;
private Long saldoawal;
private Integer tracenumber;
private String state;
private Date createdate;
private Batch batch;
public TransactionQR() {
}
public TransactionQR(Long id, String codeqr, Date approvaltime, String merchant, String code_merchant, Long amount,
Long saldoawal, Integer tracenumber, String state, Date createdate, Batch batch) {
super();
this.id = id;
this.codeqr = codeqr;
this.approvaltime = approvaltime;
this.merchant = merchant;
this.code_merchant = code_merchant;
this.amount = amount;
this.saldoawal = saldoawal;
this.tracenumber = tracenumber;
this.state = state;
this.createdate = createdate;
this.batch = batch;
}
public Long getId() {
return id;
}
public Date getApprovalTime() {
return approvaltime;
}
public Batch getBatch() {
return batch;
}
public void setBatch(Batch batch) {
this.batch = batch;
}
public void setApprovalTime(Date approvalTime) {
this.approvaltime = approvalTime;
}
public void setId(Long id) {
this.id = id;
}
public Date getApprovaltime() {
return approvaltime;
}
public void setApprovaltime(Date approvaltime) {
this.approvaltime = approvaltime;
}
public String getCodeqr() {
return codeqr;
}
public void setCodeqr(String codeqr) {
this.codeqr = codeqr;
}
public String getMerchant() {
return merchant;
}
public void setMerchant(String merchant) {
this.merchant = merchant;
}
public String getCode_merchant() {
return code_merchant;
}
public void setCode_merchant(String code_merchant) {
this.code_merchant = code_merchant;
}
public Long getAmount() {
return amount;
}
public void setAmount(Long amount) {
this.amount = amount;
}
public Long getSaldoawal() {
return saldoawal;
}
public void setSaldoawal(Long saldoawal) {
this.saldoawal = saldoawal;
}
public Integer getTracenumber() {
return tracenumber;
}
public void setTracenumber(Integer tracenumber) {
this.tracenumber = tracenumber;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Date getCreatedate() {
return createdate;
}
public void setCreatedate(Date createdate) {
this.createdate = createdate;
}
}
i have try to handle the list with Gson:
Gson objGson = new GsonBuilder().setPrettyPrinting().create();
String json = objGson.toJson(QR.getAllTransaction());
System.out.println(json);
in that way, it's work to show but it's not from POJO right i want work with pojo to parse the data to json ?
why i get the error can't cast to model ? any clue ?
Try adding Select tr to your query in getAllTransaction()
Wich is the relation between QRTransactionDao and TransactionQR ?

How to convert JSON String into Arraylist of Objects

I have JSON String, received from HTTP request:
[
{
"id":15,
"title":"1",
"description":"desc",
"user_id":152
},
{
"id":18,
"title":"2",
"description":"desc",
"user_id":152
},
{
"id":19,
"title":"tab3",
"description":"zadanka",
"user_id":152
}
]
How to convert it into an ArrayList of Objects?
Using Gson
Gson gson = new Gson();
ArrayList<Object> listFromGson = gson.fromJson("json string",
new TypeToken<ArrayList<Object>>() {}.getType());
Using Jackson
ObjectMapper mapper = new ObjectMapper();
ArrayList<Object> listFromJackson = mapper.readValue("json string",
new TypeReference<ArrayList<Object>>(){});
If you could define a pojo as
public class Example {
private Integer id;
private String title;
private String description;
private Integer userId;
// setters / getters
}
Then
ArrayList<Example> listFromGson = gson.fromJson("json string",
new TypeToken<ArrayList<Example>>() {}.getType());
ArrayList<Example> listFromJackson = mapper.readValue("json string",
new TypeReference<ArrayList<Example>>(){});
Also, you should prefer using List instead of ArrayList.
You need to declare a pojo
class Data{
String id;
String title;
String description;
String userId;
//Generate setter an getter
}
The iterate over json like following:
JSONArray jsonArr = new JSONArray("[your JSON Stirng]");
List<Data> dataList = new ArrayList<Data>();
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
Data data = new Data();
data.setId(jsonObj.getString("id"));
data.setTitle(jsonObj.getString("title"));
data.setDescription(jsonObj.getString("description"));
data.setUserId(jsonObj.getString("user_id"));
dataList.add(data);
}
You also need json jar. You can download from here
If you are using RestApi then use the annotation #RequestBody with your pojo class.
#RequestMapping(value="/your api name", method=RequestMethod.POST)
public ResponseData createUser(#RequestBody MyPojo myPojo){
System.out.println("Creating User "+myPojo.toString());
//Here you will able to access your request data from myPojo object
}
Make your pojo class:
public class MyPojo
{
private Data[] data;
public Data[] getData ()
{
return data;
}
public void setData (Data[] data)
{
this.data = data;
}
#Override
public String toString()
{
return "ClassPojo [data = "+data+"]";
}
}
public class Data
{
private String id;
private String title;
private String description;
private String user_id;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
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;
}
public String getUser_id ()
{
return user_id;
}
public void setUser_id (String user_id)
{
this.user_id = user_id;
}
#Override
public String toString()
{
return "ClassPojo [id = "+id+", title = "+title+", description = "+description+", user_id = "+user_id+"]";
}
}
In addition to #Sudhir, I would recommend to use Gson
Gson gson = new GsonBuilder().create();
Data p = gson.fromJson(jsonString, Data.class);
// Or to array.
Data[] data = gson.fromJson(jsonString, Data[].class);

Hibernate java.util.ArrayList cannot be cast.. Class cast exception

I am trying to read certain values from the hsql db and these values are returned as map with key and value. I have one more method which will accept these map values and will iterate through it and will fetch certain values based on the conditions.After this it will add all these values to a list. for me the condition and the first method is working fine but while adding the values to the list I am facing the class cast exception
Method which reads values from the table:
List<EntityMap> sample = session.createQuery(" FROM EntityMap order by if.ifName").list();
for (Iterator<EntityMap> iterator = sample.iterator(); iterator.hasNext();) {
entityMap = (EntityMap) iterator.next();
if (IfName != entityMap.getIf().getIfName().toString()) {
IfName = entityMap.getIf().getIfName().toString();
entitymapobject = new ArrayList<EntityMap>();
}
entitymapobject.add(entityMap);
EntityMaplist.put(entityMap.getIf().getIfName(),entitymapobject);
}
tx.commit();
This method is returning a map and it has the values which is fetched from the db. After that i am trying to extract certain values based on some conditions.In this I am calling the above method and i am iterating through it
proertyMap = listPROPERTNAMES();
System.out.println("inside loadproperty");
for (Iterator<Integer> itr1 = srcEntityIDList.iterator(); itr1.hasNext();) {
Integer aInteger = itr1.next();
for (Map.Entry<Long, List<PropertyMap>> entry : proertyMap.entrySet()) {
System.out.println(aInteger);
System.out.println(entry.getKey());
Long aLong = entry.getKey();
if (aLong.equals(Long.valueOf(aInteger))) {
System.out.println("values are equal");
trgtPropNameList.add(( (PropertyMap) entry.getValue()).getTgtpropnm());
}
}
}
return trgtPropNameList;
if (tx != null)
tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
return EntityMaplist;
}
Here while trying to add the values to the list (trgtPropNameList) I am getting a class cast exception. My POJO class which has the setter and the getter methods is
public class PropertyMap implements java.io.Serializable {
private PropertyMapId id;
private EntityMap entityMap;
private String tgtpropnm;
private String splitrule;
private String combinerule;
private String createdby;
private Date createdon;
public PropertyMap() {
}
public PropertyMap(PropertyMapId id, EntityMap entityMap) {
this.id = id;
this.entityMap = entityMap;
}
public PropertyMap(PropertyMapId id, EntityMap entityMap, String tgtpropnm,
String splitrule, String combinerule, String createdby,
Date createdon) {
this.id = id;
this.entityMap = entityMap;
this.tgtpropnm = tgtpropnm;
this.splitrule = splitrule;
this.combinerule = combinerule;
this.createdby = createdby;
this.createdon = createdon;
}
public PropertyMapId getId() {
return this.id;
}
public void setId(PropertyMapId id) {
this.id = id;
}
public EntityMap getEntityMap() {
return this.entityMap;
}
public void setEntityMap(EntityMap entityMap) {
this.entityMap = entityMap;
}
public String getTgtpropnm() {
return this.tgtpropnm;
}
public void setTgtpropnm(String tgtpropnm) {
this.tgtpropnm = tgtpropnm;
}
public String getSplitrule() {
return this.splitrule;
}
public void setSplitrule(String splitrule) {
this.splitrule = splitrule;
}
public String getCombinerule() {
return this.combinerule;
}
public void setCombinerule(String combinerule) {
this.combinerule = combinerule;
}
public String getCreatedby() {
return this.createdby;
}
public void setCreatedby(String createdby) {
this.createdby = createdby;
}
public Date getCreatedon() {
return this.createdon;
}
public void setCreatedon(Date createdon) {
this.createdon = createdon;
}
}
Can anyone please help me here?
entry.getValue() is an object of type List<PropertyMap> and not PropertyMap
If you can't cast it just construct and fill a new one.
Change the line
trgtPropNameList.add(( (PropertyMap) entry.getValue()).getTgtpropnm());
to
for(PropertyMap map : entry.getValue(){
trgtPropNameList.add(((PropertyMap)map).getTgtpropnm());
}
Should fix the casting problem.

Categories