How wrap json array to custom object with collection containing this array via Gson? I have following json string:
[
{
"showId":410,
"siteId":85,
"name":"Майстер і маргарита",
"duration":7200,
"providerId":1016,
"events":[
{
"siteId":85,
"eventSiteId":0,
"providerId":1016,
"eventId":1178,
"hallId":0,
"premiere":false,
"origin":"20140912190000"
}
]
}
]
and want to deserialize it to the object bellow:
public class Shows {
private List<Show> shows;
public List<Show> getShows() {
return shows;
}
public void setShows(List<Show> shows) {
this.shows = shows;
}
}
This Json message is represent a List<Show> that Show contains a List of Events as well.
This is not a Json of Shows, if so it should be like this.
{
"shows":[
{
"showId":410,
"siteId":85,
"name":"Майстер і маргарита",
"duration":7200,
"providerId":1016,
"events":[
{
"siteId":85,
"eventSiteId":0,
"providerId":1016,
"eventId":1178,
"hallId":0,
"premiere":false,
"origin":"20140912190000"
}
]
}
]
}
But you can try this way to get List<Show> and set it to Shows
You can try this way.
Type collectionType = new TypeToken<List<Show>>() {
}.getType();
String jsonString="[\n" +
"\n" +
" {\n" +
" \"showId\":410,\n" +
" \"siteId\":85,\n" +
" \"name\":\"Майстер і маргарита\",\n" +
" \"duration\":7200,\n" +
" \"providerId\":1016,\n" +
" \"events\":[\n" +
" {\n" +
" \"siteId\":85,\n" +
" \"eventSiteId\":0,\n" +
" \"providerId\":1016,\n" +
" \"eventId\":1178,\n" +
" \"hallId\":0,\n" +
" \"premiere\":false,\n" +
" \"origin\":\"20140912190000\"\n" +
" }\n" +
" ]\n" +
" }\n" +
"\n" +
"]";
List<Show> showList=new Gson().fromJson(jsonString,collectionType);
Shows shows=new Shows();
shows.setShows(showList);
System.out.println(shows);
My result.
Shows{shows=[Show{showId=410, siteId=85, name='Майстер і маргарита',
duration=7200, providerId=1016, events=[Events{siteId=85,
eventSiteId=0, providerId=1016, eventId=1178, hallId=0,
premiere=false, origin='20140912190000'}]}]}
My Show class.
public class Show {
private int showId;
private int siteId;
private String name;
private int duration;
private int providerId;
private List<Events> events;
//getters and setters
#Override
public String toString() {
return "Show{" +
"showId=" + showId +
", siteId=" + siteId +
", name='" + name + '\'' +
", duration=" + duration +
", providerId=" + providerId +
", events=" + events +
'}';
}
}
My Events class
public class Events {
private int siteId;
private int eventSiteId;
private int providerId;
private int eventId;
private int hallId;
private boolean premiere;
private String origin;
// getters and setters
#Override
public String toString() {
return "Events{" +
"siteId=" + siteId +
", eventSiteId=" + eventSiteId +
", providerId=" + providerId +
", eventId=" + eventId +
", hallId=" + hallId +
", premiere=" + premiere +
", origin='" + origin + '\'' +
'}';
}
}
You can try this.
//lets assume the json string to be in the variable data
Shows shows = new Gson().fromJson(data, Shows.class);
Related
I have a json file called file.json which has a contents as following.
[
{
"symbol": "AAPL",
"quantity": 100,
"tradeType": "BUY",
"purchaseDate": "2019-01-02"
},
{
"symbol": "MSFT",
"quantity": 10,
"tradeType": "BUY",
"purchaseDate": "2019-01-02"
},
{
"symbol": "GOOGL",
"quantity": 50,
"tradeType": "BUY",
"purchaseDate": "2019-01-02"
}
]
I need to get the values under the field symbol as a list as ["AAPL","MSFT","GOOGL"] in JAVA using ObjectMapper. Any suggestions as to how can I get the values in the symbol? For one single json entry I have found articles as to how map the values using POJOs using getters and setters. Can I do the same for this problem? How ?
POJO
class Stock {
private String symbol;
private float quantity;
private String tradeType;
private String purchaseDate;
public String getSymbol(){
return this.symbol;
}
public float getQuantity(){
return this.quantity;
}
public String getTradeType(){
return this.tradeType;
}
public String getPurchaseDate(){
return this.purchaseDate;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public void setQuantity(float quantity) {
this.quantity = quantity;
}
public void setTradeType(String tradeType) {
this.tradeType = tradeType;
}
public void setPurchaseDate(String purchaseDate) {
this.purchaseDate = purchaseDate;
}
}
Yes you can do it.
Your JSON represents an array of objects. So, you can use the readValue method provided by Jackson and get an array of Java objects. This is where your pojo will come into play, since it will be representing the objects.
Stock[] stockArr = mapper.readValue(YourJson, Stock[].class);
You can then access elements in the array and call your getters on them.
stockArr[0].getSymbol();
To get all of the symbols simply loop through the array :)
#Test
public void testSymbols() throws IOException {
String json = "[\n" + " {\n" + " \"symbol\": \"AAPL\",\n" + " \"quantity\": 100,\n" + " \"tradeType\": \"BUY\",\n"
+ " \"purchaseDate\": \"2019-01-02\"\n" + " },\n" + " {\n" + " \"symbol\": \"MSFT\",\n"
+ " \"quantity\": 10,\n" + " \"tradeType\": \"BUY\",\n" + " \"purchaseDate\": \"2019-01-02\"\n" + " },\n"
+ " {\n" + " \"symbol\": \"GOOGL\",\n" + " \"quantity\": 50,\n" + " \"tradeType\": \"BUY\",\n"
+ " \"purchaseDate\": \"2019-01-02\"\n" + " }\n" + "]";
List list = objectMapper.readValue(json ,List.class);
List<String> symList = new ArrayList<>();
list.stream().map( m-> ((LinkedHashMap) m).get("symbol")).forEach( o->{
symList.add((String)o);
});
System.out.println(symList);
}
// output : [AAPL, MSFT, GOOGL]
I have
data= [{
id=1,
employee_name=Tiger Nixon,
employee_salary=320800,
employee_age=61,
profile_image=
},
{
id=2,
employee_name=Garrett Winters,
employee_salary=170750,
employee_age=63,
profile_image=
},
{
id=3,
employee_name=Ashton Cox,
employee_salary=86000,
employee_age=66,
profile_image=
},
{
id=4,
employee_name=Cedric Kelly,
employee_salary=433060,
employee_age=22,
profile_image=
}
]
I have employee class
public class Employee {
private String employee_name;
private String employee_salary;
private String employee_age;
private String id;
private String profile_image;
public String toCsvRow() {
String csvRow = "";
for (String value : Arrays.asList(employee_name,employee_salary,employee_age)) {
String processed = value;
if (value.contains("\"") || value.contains(",")) {
processed = "\"" + value.replaceAll("\"", "\"\"") + "\"";
}
csvRow += "," + processed;
}
return csvRow.substring(1);
}
public String getEmployee_name() {
return employee_name;
}
public String getEmployee_salary() {
return employee_salary;
}
public String getEmployee_age() {
return employee_age;
}
}
I tried for
Map<String, ArrayList<Employee>> map = mapper.readValue(url, Map.class);
ArrayList<Employee> emps = map.get("data");
emps.get(0).toCsvRow()
Exception in thread "main" java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to org.example.model.Employee
Now I cannot call toCSVRow using emps.
Use Gson to parse JSON to ArrayList, for CSV conversion you can use org.json.CDL
See this is working fine
String str = "[{" +
" id=1," +
" employee_name=\"Tiger Nixon\"," +
" employee_salary=320800," +
" employee_age=61," +
" profile_image=\"khkjh\"" +
" }," +
" {" +
" id=2," +
" employee_name=\"Garrett Winters\"," +
" employee_salary=170750," +
" employee_age=63," +
" profile_image=\"\"" +
" }," +
" {" +
" id=3," +
" employee_name=\"Ashton Cox\"," +
" employee_salary=86000," +
" employee_age=66," +
" profile_image=\"\"" +
" }," +
" {" +
" id=4," +
" employee_name=\"Cedric Kelly\"," +
" employee_salary=433060," +
" employee_age=22," +
" profile_image=\"\"" +
" }" +
" ]";
try{
Gson gson = new Gson();
ArrayList<Employee> list = gson.fromJson(str, ArrayList.class);
String csv = CDL.toString(new JSONArray(list));
}catch (Exception e){
e.printStackTrace();
}
Output:
id,employee_name,employee_salary,employee_age,profile_image
1.0,Tiger Nixon,320800.0,61.0,khkjh
2.0,Garrett Winters,170750.0,63.0,
3.0,Ashton Cox,86000.0,66.0,
4.0,Cedric Kelly,433060.0,22.0
People, I need help, if anyone can help me, I thank you!
I am getting a JSON and wanted to know if I can bring the information to a LIST of my model.
is a call to send 1 SMS
This is the first time I try to do something with JSON
my model has all getters and setters.
Model
public class Zenvia {
#JsonProperty("sendSmsResponse")
private String sendSmsResponse;
//Request
#JsonProperty("id")
private String id;
#JsonProperty("from")
private String from;
#JsonProperty("to")
private String to;
#JsonProperty("msg")
private String msg;
#JsonProperty("schedule")
private String schedule;
#JsonProperty("callbackOption")
private String callbackOption;
#JsonProperty("aggregateId")
private String aggregateId;
#JsonProperty("flashSms")
private boolean flashSms;
//Response
private long stats;
#JsonProperty("statusCode")
private String statusCode;
#JsonProperty("statusDescription")
private String statusDescription;
#JsonProperty("detailCode")
private String detailCode;
#JsonProperty("detailDescription")
private String detailDescription;
#JsonProperty("mobileOperatorName")
private String mobileOperatorName;
#JsonProperty("received")
private String received;
//getters and setters
}
my call
public Zenvia senderUnique(Zenvia zenvia) {
Response response = null;
try {
Client client = ClientBuilder.newClient();
Entity payload = Entity.json(" {\n"
+ " \"sendSmsRequest\": {\n"
+ " \"from\": \"" + zenvia.getFrom() + "\",\n"
+ " \"to\": \"" + zenvia.getTo() + "\",\n"
+ " \"schedule\": \"" + zenvia.getSchedule() + "\",\n"
+ " \"msg\": \"" + zenvia.getMsg() + "\",\n"
+ " \"callbackOption\": \"" + zenvia.getCallbackOption() + "\",\n"
+ " \"id\": \"" + zenvia.getId() + "\",\n"
+ " \"aggregateId\": \"" + zenvia.getAggregateId() + "\",\n"
+ " \"flashSms\": " + zenvia.isFlashSms() + "\n"
+ " }\n"
+ " }");
response = client.target("https://api-rest.zenvia360.com.br/services/send-sms")
.request(MediaType.APPLICATION_JSON_TYPE)
.header("Authorization", "Basic ***********")
.header("Accept", "application/json")
.post(payload);
System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
response.close();
} catch (Exception e) {
e.printStackTrace();
}
return zenvia;
}
at this point I have this return, which is the best practice of consuming this data, I have a model prepared to receive this information.
converting to a LIST?
as?
string JSON response that im getting
body:{
"sendSmsMultiResponse" : {
"sendSmsResponseList" : [ {
"statusCode" : "10",
"statusDescription" : "Error",
"detailCode" : "080",
"detailDescription" : "Message with same ID already sent"
}, {
"statusCode" : "10",
"statusDescription" : "Error",
"detailCode" : "080",
"detailDescription" : "Message with same ID already sent"
}, {
"statusCode" : "10",
"statusDescription" : "Error",
"detailCode" : "080",
"detailDescription" : "Message with same ID already sent"
} ]
}
}
can be one or more results, so is a list.
You can read the response to a String and then Map it to your Entity class using jackson
ObjectMapper mapper = new ObjectMapper();
String jsonInString = response.readEntity(String.class);
//Convert JSON from String to Object
List<YourEntityModelObject> objList = mapper.readValue(jsonInString, new TypeReference<List<YourEntityModelObject>>(){});
I am trying to get response text from Java server using getJSON() jQuery method. Although, I can get response data when the Java class is simple format (String, List and Map), I could not get success data when using other Java object.
The following is Java class which is using a simple type and I get the success result with data that works:
package com.awitd.framework.action;
import com.opensymphony.xwork2.Action;
public class getAllJson implements Action{
private String data;
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public String execute() {
System.out.println(" this is from action");
data = "[";
data += "{";
data += "\"objid\":\"" + "1" + "\",";
data += "\"id\":\"" + "1" + "\",\"name\":\"" + "name" + "\"";
data += "}"; System.out.println("data " + data);
data += "]";
return SUCCESS;
}
}
The following is Java class which is using other Java object and it doesn't return a success data:
package com.awitd.framework.action;
import java.util.List;
import com.opensymphony.xwork2.Action;
import com.awitd.framework.entity.Employee;
import com.awitd.framework.entity.Profile;
import com.awitd.framework.service.EmployeeService;
public class getAllJson implements Action{
private String data;
private EmployeeService employeeService;
private List<Employee> employeeList;
private Employee employee;
private Profile profile;
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public EmployeeService getEmployeeService() {
return employeeService;
}
public void setEmployeeService(EmployeeService employeeService) {
this.employeeService = employeeService;
}
public String execute() {
System.out.println(" this is from action");
data = "[";
/*data += "{";
data += "\"objid\":\"" + "1" + "\",";
data += "\"id\":\"" + "1" + "\",\"name\":\"" + "name" + "\"";
data += "}"; System.out.println("data " + data);*/
employeeList = employeeService.getAll();
System.out.println("size........"+employeeList.size());
if (!employeeList.isEmpty()) {
for (int i=0; i<employeeList.size(); i++) {
employee = employeeList.get(i);
profile = employee.getProfile();
data += "{";
data += "\"objid\":\"" + employee.getEmployeeId() + "\",";
data += "\"id\":\"" + employee.getId() + "\",\"name\":\"" + employee.getName() + "\"";
data += ",\"dob\":\"" + profile.getDob() + "\",\"sex\":\"" + profile.getSex() + "\"";
data += ",\"email\":\"" + profile.getEmail() + "\",\"workstart\":\"" + profile.getWorkstart() + "\"";
data += ",\"study\":\"" + profile.getStudySub() + "\",\"jplevel\":\"" + profile.getJpLevel() + "\"";
data += ",\"jpgroup\":\"" + profile.getJpGroup() + "\",\"remark\":\"" + profile.getRemark() + "\"";
data += "}";
if (!(i==employeeList.size()-1))
data += ",";
}
}
data += "]";
return SUCCESS;
}
}
Got this error:
No existing transaction found for transaction marked with propagation 'mandatory'
java.lang.reflect.InvocationTargetException
org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException:
org.apache.struts2.json.JSONException: java.lang.reflect.InvocationTargetException
org.apache.struts2.json.JSONWriter.bean(JSONWriter.java:246)
org.apache.struts2.json.JSONWriter.processCustom(JSONWriter.java:178)
org.apache.struts2.json.JSONWriter.process(JSONWriter.java:168)
org.apache.struts2.json.JSONWriter.value(JSONWriter.java:134)
org.apache.struts2.json.JSONWriter.write(JSONWriter.java:102)
org.apache.struts2.json.JSONUtil.serialize(JSONUtil.java:116)
org.apache.struts2.json.JSONResult.createJSONString(JSONResult.java:196)
org.apache.struts2.json.JSONResult.execute(JSONResult.java:170)
com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:367)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:271)
Try the following code, it should fix the error
data += "{";
data += "\"objid\":\"" + employee.getEmployeeId() + "\",";
data += "\"id\":\"" + employee.getId() + "\",\"name\":\"" + employee.getName() + "\",";
data += ",\"dob\":\"" + profile.getDob() + "\",\"sex\":\"" + profile.getSex() + "\",";
data += ",\"email\":\"" + profile.getEmail() + "\",\"workstart\":\"" + profile.getWorkstart() + "\",";
data += ",\"study\":\"" + profile.getStudySub() + "\",\"jplevel\":\"" + profile.getJpLevel() + "\",";
data += ",\"jpgroup\":\"" + profile.getJpGroup() + "\",\"remark\":\"" + profile.getRemark() + "\"";
data += "}";
i am trying to parse following json file.
"ItemData" : [{
"-item" : "A",
"id" : "100",
"name" : "abc",
"description" : "abcd",
"category" : "xyz",
}
]
I am able to parse everything except first field. Its because of "-" character in the beginning. I tried using #SerializedName("-item") in my POJO file. But does not work.
Can anybody tell me how can i parse this field?
I am not sure how your code looks like but #SerializedName("-item") seems to be working fine for me
class Data {
private List<ItemData> ItemData = new ArrayList<ItemData>();
#Override
public String toString() {
return "Data [ItemData=" + ItemData + "]";
}
}
class ItemData {
#SerializedName("-item")
private String _item;
private String id;
private String name;
private String description;
private String category;
#Override
public String toString() {
return "ItemData [_item=" + _item + ", id=" + id + ", name=" + name
+ ", description=" + description + ", category=" + category
+ "]";
}
}
Usage
Gson gson = new Gson();
String jsonString = "{\r\n" + " \"ItemData\" : [{\r\n"
+ " \"-item\" : \"A\",\r\n" + " \"id\" : \"100\",\r\n"
+ " \"name\" : \"abc\",\r\n"
+ " \"description\" : \"abcd\",\r\n"
+ " \"category\" : \"xyz\"\r\n" + " }\r\n" + " ]\r\n"
+ "}\r\n";
Data item = gson.fromJson(jsonString, Data.class);
System.out.println(item);
Output
Data [ItemData=[ItemData [_item=A, id=100, name=abc, description=abcd, category=xyz]]]
^^^^^^^