How to convert specific JSONArray to JAVA object? - java

In Java project I used WebSocket to get subscription and I get many different responses from socket as JSONArray, the one which I need looks as below:
[
68,
"te",
[
80588348,
1508768162000,
0.01569882,
5700.8
]
]
How should look JAVA object for this response?
How can I convert it to this object?
[
68, <- Integer
"te", <- String
[
80588348, <- Long
1508768162000, <- Long
0.01569882, <- Double
5700.8 <- Double
]
]
There is one problem that there are other responses like:
{"event":"subscribed","channel":"trades","chanId":68,"symbol":"tBTCUSD","pair":"BTCUSD"}
And when I try convert it by new JSONArray(response) it throws org.json.JSONException: A JSONArray text must start with '[' at 1 [character 2 line 1].
How to get and convert this fields which I need(the first response example) ?
I want get something like this:
public class Details{
public Long id;
public Long timestamp;
public Double amount;
public Double price;
}
public class Response{
public Integer id;
public String type;
public Details details;
}

The parser class as requested:
public class JsonParser {
public static Response toJavaObject(String str) {
String[] fields = str.split(",");
Response res = new Response();
res.setId(Integer.valueOf(fields[0].substring(1)));
res.setType(fields[1].replaceAll("\"", ""));
Details dtl = new Details();
dtl.setId(Long.valueOf(fields[2].substring(1)));
dtl.setTimestamp(Long.valueOf(fields[3]));
dtl.setAmount(Double.valueOf(fields[4]));
dtl.setPrice(Double.valueOf(fields[5].substring(0, fields[5].length() - 2)));
res.setDetails(dtl);
return res;
}
}
class Details {
public Long id;
public Long timestamp;
public Double amount;
public Double price;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getTimestamp() {
return timestamp;
}
public void setTimestamp(Long timestamp) {
this.timestamp = timestamp;
}
public Double getAmount() {
return amount;
}
public void setAmount(Double amount) {
this.amount = amount;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
}
class Response {
public Integer id;
public String type;
public Details details;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Details getDetails() {
return details;
}
public void setDetails(Details details) {
this.details = details;
}
}
To make use of this JsonParser,
for example in your code now:
public static void main(String args[]) {
String str = "[68,\"te\",[80588348,1508768162000,0.01569882,5700.8]]";
Response res = JsonParser.toJavaObject(str);
// your logic below...
}

If your response is in fixed format,
example:
JSONString : {"color":"yellow","type":"renault"}
In Java, you can use the following code:
Car car = objectMapper.readValue(jsonString, Car.class);
Where you have the Car class as:
public class Car {
private String color;
private String type;
// standard getters setters
}

Related

JSON parse error: Cannot deserialize instance of.. out of START_ARRAY token

I know there are a few questions on stackoverflow regarding this problem. But I have have been spending hours trying to resolve this error without any success.
I am using the mysql database to store the values.
I keep on getting the error message from the
com.example.springboot.Recipe file.
This is springboot recipe file
package com.example.springboot;
import com.example.springboot.Recipe;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
#Entity // This tells Hibernate to make a table out of this class
public class Recipe {
public Recipe(){
}
public Recipe(Integer id, String name, String description, String type, Integer preptime, Integer cooktime, String content, Integer difficulty){
this.id = id;
this.name = name;
this.description = description;
this.type = type;
this.preptime = preptimee;
this.cooktime = cooktime;
this.content = content;
this.difficulty = difficulty;
}
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String name;
private String description;
private String type;
private Integer preptime;
private Integer cooktime;
#Column(columnDefinition = "TEXT")
private String content;
private Integer difficulty;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return name;
}
public void setTitle(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Integer getDifficulty() {
return difficulty;
}
public void setDifficulty(Integer difficulty) {
this.difficulty = difficulty;
}
public Integer getCookingtime() {
return cooktime;
}
public void setCookingtimeime(Integer cooktime) {
this.cooktime = cooktime;
}
public Integer getPreparationtime() {
return preptime;
}
public void setPreparationtime(Integer preptime) {
this.preptime = preptime;
}
}
Main Controller:
#PutMapping("/recipes/edit/{id}")
void updateRecipe2(#PathVariable int id, #RequestBody Recipe recipe ) {
Recipe recipe_ = recipeRepository.findById(id).get();
recipe_.setTitle(recipe.getTitle());
System.out.println("sss " + recipe.getname());
System.out.println("change");
recipeRepository.save(recipe_);
}
service.ts:
updateRecipe2 (id: number, recipe: any): Observable<any > {
const url = `${this.usersUrl}/edit/${id}`;
return this.http.put(url ,recipe);
}
where the updateRecipe2 gets called:
save(): void {
const id = +this.route.snapshot.paramMap.get('name');
this.recipeService.updateRecipe2(id, this.recipes)
.subscribe(() => this.gotoUserList());
}
as soon as the user clicks save this functions saves the changes made.
I hope the code snippets that I provided are enough to help solve the problem.
Thank you in advance.
I am building a rest api with spring boot and I am using angularjs as it's frontend. I am pretty new to web-development.
You are sending a list of recipes to an api endpoint that expects a single recipe object.
Your options are:
Send only one recipe object at a time, for example:
this.recipeService.updateRecipe2(id, this.recipes[0])
OR: create a new API endpoint to accept a list of recipes, to edit them in "batch"
#PutMapping("/recipes/edit")
void updateRecipes(#RequestBody List<Recipe> recipe ) {
my Example:
Use:
#PostMapping
Code:
public void setTransacciones(List<Transacciones> transacciones) {
this.transacciones = transacciones;
}
CodeBean:
public class Transacciones {
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
private String text;
}
Post(raw):
{
"transacciones" : [ {"text" : "1"}, {"text" : "2"} ]
}
Result:
{
"transacciones": [
{
"transaccionId": 2,
"text": "1"
},
{
"transaccionId": 3,
"text": "2"
}
]
}
BINGO!!

How to read JSON array values in Spring controller

I would like to iterate Products and get the list of name,code and price and set in my Model class. Any help would be really appreciated - how can I iterate this. When I use obj.get("Products") - it just printing as string - got stuck to iterate.
{
"id": "skd3303ll333",
"Products": [{
"name": "apple",
"code": "iphone-393",
"price": "1939"
},
{
"name": "ipad",
"code": "ipad-3939",
"price": "900"
}
]
}
#PostMapping(path="/create", consumes=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> create(#RequestBody Map<String, Object> obj ) {
System.out.println("Products :" + obj.get("Products"));
}
There are two ways to do this,
1) By type casting (personally i will not prefer this)
List<Map<Object,Object>> productslist = (List<Map<Object, Object>>) obj.get("products");
for(Map entry: productslist) {
for(Object s: entry.keySet()) {
System.out.println(s.toString());
System.out.println(entry.get(s).toString());
}
}
2) Mapping directly to Model class, for this approach you need Jackson library in buildpath
#JsonIgnoreProperties(unknown =true)
public class Customer {
#JsonProperty("id")
private String id;
#JsonProperty("products")
private List<Products> products;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public List<Products> getProducts() {
return products;
}
public void setProducts(List<Products> products) {
this.products = products;
}
}
#JsonIgnoreProperties(unknown =true)
class Products{
#JsonProperty("name")
private String name;
#JsonProperty("code")
private String code;
#JsonProperty("price")
private String price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
Controller
public ResponseEntity<Object> create(#RequestBody Customer obj ) {
You need POJO structure with two classes:
public class Product {
private String name;
private String code;
private int price;
}
public class ProductsGroup {
private long id;
private List<Product> products;
// getters/setters
}
And change your method signature to:
#PostMapping(path="/create", consumes=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ProductsGroup> create(#RequestBody ProductsGroup productGroup)
{
System.out.println("Products :" + productGroup.getProducts());
}
You are trying to process the json using a Map<String, Object> obj, which could be possible in some way, but mostly what you want to do is define a single or multiple POJO classes. These represent the json.
public class IdWrapper {
private String id;
#JsonProperty("Products")
private List<Product> products;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public List<Product> getProducts() {
return products;
}
}
public class Product {
private String name;
private String code;
private String price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
And in you controller like this:
#RestController
#RequestMapping("test")
public class DemoController {
#PostMapping()
public void test(#RequestBody IdWrapper productsWrapper) {
System.out.println();
}
}

show all list query java hibernate

i have this function to query in hibernate:
public List<TransactionQR> getAllTransaction() throws HibernateException {
return this.session.createQuery("SELECT id FROM TransactionQR").list();
}
then is success to show the data like this in html:
[2, 3]
but when i add more column in SELECT like this:
public List<TransactionQR> getAllTransaction() throws HibernateException {
return this.session.createQuery("SELECT id, codeqr FROM TransactionQR").list();
}
the result show like this:
[Ljava.lang.Object;#25026824, [Ljava.lang.Object;#170b75f9]
what is Ljava.lang.Object;#25026824 ? is return object, can i handle it to convert from list to json ?
i have model TransactionQR.java :
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;
}
}
the result is i want to show all data from database in list
In second case, since you are selecting two attributes, that is why session.createQuery("").list returns a list of object array(List<Object[]>) . At each index of list you will find an object array. Each array will have two indexes. First index will provide id while the second one would provide codeqr. So, basically you need to iterate over the list. Then fetch each value individually like arr[0], arr[1]..

Gson deserializes with empty fields

The result variable contains corrected parsed JSON.
But after deserialization List contains correct amount of items but all of them are empty.
How to fix it?
Gson gson = new Gson();
List<UnitView> unitViews = new ArrayList<UnitView>();
// https://stackoverflow.com/questions/5554217/google-gson-deserialize-listclass-object-generic-type
Type typeToken = new TypeToken<List<UnitView>>() { }.getType();
unitViews = gson.fromJson(result,typeToken);
Even if I do like
UnitView[] unitViews = gson.fromJson(result, UnitView[].class);
The fields of items are empty as well.
UnitView
public class UnitView implements Serializable {
public String id ;
public String name ;
public String description ;
public String deviceTypeName ;
public String categoryID ;
public String lastOnline ;
public String latitude ;
public String longitude ;
public String atTime ;
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public String getDeviceTypeName() {
return deviceTypeName;
}
public String getCategoryID() {
return categoryID;
}
public String getLastOnline() {
return lastOnline;
}
public String getLatitude() {
return latitude;
}
public String getLongitude() {
return longitude;
}
public String getAtTime() {
return atTime;
}
public void setId(String id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setDescription(String description) {
this.description = description;
}
public void setDeviceTypeName(String deviceTypeName) {
this.deviceTypeName = deviceTypeName;
}
public void setCategoryID(String categoryID) {
this.categoryID = categoryID;
}
public void setLastOnline(String lastOnline) {
this.lastOnline = lastOnline;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public void setAtTime(String atTime) {
this.atTime = atTime;
}
}
JSON DATA
[{"ID":"294","Name":"Foton Tunland № F110","Description":null,"DeviceTypeName":"Техника ТО","CategoryID":"18","LastOnline":"19.12.2017 20:38:04","Latitude":"11,40119","Longitude":"11,42403","AtTime":"19.12.2017 20:38:04"},{"ID":"295","Name":"DML LP1200 № 9793","Description":null,"DeviceTypeName":"Буровой станок дизельный","CategoryID":"15","LastOnline":null,"Latitude":null,"Longitude":null,"AtTime":null}]
Ok , the problem is that the parser is case-sensitive, you can change the name of your attributes to match the name of the json value of you could use the SerializedName annotation like this:
#SerializedName("ID")
public String id ;
#SerializedName("Name")
public String name ;
#SerializedName("Description")
public String description;
...
or
public String ID ;
public String Name ;
public String Description ;
...
I think you're having this problem because of null values in your json.
Check it. Source

How to parse JSON using GSON?

How get value in array "rate" to invoke getters methods ?
My Json response is something as below and confused how to parse it using GSON. Please have look on the following and guide me how i can parse it using GSON.
data.json
{
"query":{
"count":2,
"created":"2017-01-03T12:45:19Z",
"lang":"en-us",
"results":{
"rate":[
{
"id":"BTC/USD",
"Name":"BTCUSD",
"Rate":"985.50",
"Date":"1/3/2017",
"Time":"10:35am",
"Ask":"985.50",
"Bid":"985.35"
},
{
"id":"BTC/EUR",
"Name":"BTCEUR",
"Rate":"973.16",
"Date":"1/3/2017",
"Time":"10:35am",
"Ask":"973.16",
"Bid":"973.10"
}
]
}
}
}
I use classes to parse apart
Market.java
public class Market {
#SerializedName("query")
private Query query;
public Query getQuery() {
return query;
}
public void setQuery(Query query) {
this.query = query;
}
}
Query.java
public class Query {
#SerializedName("count")
private Integer count;
#SerializedName("created")
private String created;
#SerializedName("lang")
private String lang;
#SerializedName("results")
private Results results;
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
public String getCreated() {
return created;
}
public void setCreated(String created) {
this.created = created;
}
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
public Results getResults() {
return results;
}
public void setResults(Results results) {
this.results = results;
}
}
Rate.java
public class Rate {
#SerializedName("id")
private String id;
#SerializedName("Name")
private String name;
#SerializedName("Rate")
private String rate;
#SerializedName("Date")
private String date;
#SerializedName("Time")
private String time;
#SerializedName("Ask")
private String ask;
#SerializedName("Bid")
private String bid;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRate() {
return rate;
}
public void setRate(String rate) {
this.rate = rate;
}
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;
}
public String getAsk() {
return ask;
}
public void setAsk(String ask) {
this.ask = ask;
}
public String getBid() {
return bid;
}
public void setBid(String bid) {
this.bid = bid;
}
}
Results.java
public class Results {
#SerializedName("rate")
private List<Rate> rate = null;
public List<Rate> getRate() {
return rate;
}
public void setRate(List<Rate> rate) {
this.rate = rate;
}
}
Trying to get the values
Main.java
public class Main {
/* ..... */
Gson gson = new Gson();
Market market = gson.fromJson(json, Market.class);
//error: incompatible types: Rate cannot be converted to List<Rate>
for( List<Rate> res : market.getQuery().getResults().getRate());
{
Log.v(LOG_TAG, res); // error: cannot find symbol variable res
}
}
how to do it properly ?
The syntax of your for each loop is incorrect. Since you are attempting to loop through a list of Rate objects, the type of res should be a Rate, not a list of Rates:
for (Rate res : market.getQuery().getResults().getRate()) {
// code here
}
As an aside, you should consider checking for null values before dereferencing all of those child objects as you run the risk of throwing a NullPointerException at runtime.

Categories

Resources