i'm trying deserialize my object, but I can not get no error!
I'm using gson on android to read json file.
My deserialize
this is my request class, i using a rest server.
public Object getListaSeguradoras(String _codPais, String _tipoPesquisa)
{
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(Config.WS_PATH);
post.setHeader("content-type", "application/json; charset=UTF-8");
post.addHeader("Client-Application","xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
//Make object in JSON format
JSONObject dato = new JSONObject();
dato.put("CodPais", _codPais);
dato.put("TipoPesquisa", _tipoPesquisa);
StringEntity entity = new StringEntity(dato.toString());
post.setEntity(entity);
HttpResponse resp = httpClient.execute(post);
String respStr = EntityUtils.toString(resp.getEntity());
Gson gson = new Gson();
Type collectionType = new TypeToken<Collection<SeguradoraLista>>(){}.getType();
Collection<SeguradoraLista> ListaSeguradoras = gson.fromJson(respStr, collectionType);
return ListaSeguradoras;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
My object:
This is my getter and setter
public class SeguradoraLista{
public String SeguradoraId;
public String Nome;
public String getSeguradoraId() {
return this.SeguradoraId;
}
public String getNome() {
return this.Nome;
}
public void setSeguradoraId ( String SeguradoraId) {
this.SeguradoraId = SeguradoraId;
}
public void setNome ( String Nome) {
this.Nome = Nome;
}
}
My json:
this is the json string on my string respStr
[{"SeguradoraId":"19","Nome":"AIG Europe"},
{"SeguradoraId":"25","Nome":"AIOI Insurance Co. Of Europe"},
{"SeguradoraId":"28","Nome":"Aktiv Forsikring A/S"},
{"SeguradoraId":"160","Nome":"Enter Forsikring AS"},
{"SeguradoraId":"167","Nome":"Euro Insurances Ltd."},
{"SeguradoraId":"189","Nome":"Försäkrings-AB Volvia"},
{"SeguradoraId":"219","Nome":"Gjensidige NOR Forsikring"},
{"SeguradoraId":"245","Nome":"If Skadeforsikring NUF"},
{"SeguradoraId":"265","Nome":"Jernbanepersonalets Forsikring Gjensiding"},
{"SeguradoraId":"271","Nome":"KLP Skadeforsikring AS"},
{"SeguradoraId":"284","Nome":"Landbruksforsikring"},
{"SeguradoraId":"309","Nome":"Lloyd's v/Vital Skade AS"},
{"SeguradoraId":"459","Nome":"SpareBank 1 Skadeforsikring AS"},
{"SeguradoraId":"472","Nome":"Tennant Forsikring nuf"},
{"SeguradoraId":"473","Nome":"Terra Skadeforsikring AS"},
{"SeguradoraId":"494","Nome":"Trygg-Hansa Forsikring Nuf"},
{"SeguradoraId":"517","Nome":"Vesta Skadeforsikring A/S"},
{"SeguradoraId":"536","Nome":"Zürich Forsikring"}]
what I'm doing wrong? I can't make this direct deserealizing?
You seem to have an array of SeguradoraLista objects.
So just create a TypeToken of type List<SeguradoraLista>
Type collectionType = new TypeToken<List<SeguradoraLista>>() {}.getType();
List<SeguradoraLista> ListaSeguradoras = gson.fromJson(respStr, collectionType);
Actually, Collection<SeguradoraLista> would work as well.
Related
i have created RequestBody with Gson and add to Post request, but in the controller of api (url), all attrs return null.
Add to RequestBody:
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
Gson gson = new Gson();
JSONObject jsonObject = new JSONObject();
jsonObject.put("dataFromAppChinh", "demo thoi");
jsonObject.put("path", path);
String body = gson.toJson(jsonObject);
RequestBody requestBody = RequestBody.create(body, JSON);
Request request = new Request.Builder().url("http://" + path + "/api/startapp").post(requestBody).build();
Controller
#RestController
#RequestMapping("/api")
public class ChatBot {
#PostMapping(value = "/startapp")
#ResponseBody
public Object start(#RequestBody() ChatBotResponse item) {
try {
item.setResponseList(startApp(item.getPath()));
return item;
} catch (Exception ex) {
log.error(ex);
return ex.getMessage();
}
}
}
My ChatBotResponse POJO:
#Data
public class ChatBotResponse
{
private String dataFromAppChinh;
private String responseList;
private String path;
}
i found problem is gson.toJson(jsonObject) insert map string before my Json String.
I changed to jsonObject.toString() and it worked.
I have a json string returning:
[{"TRAIN_JOURNEY_STAFF[],"ID":15,"EMAIL_ADDRESS":"jk#connectedrail.com","PASSWORD":"test","FIRST_NAME":"Joe","LAST_NAME":"Kevin","DATE_OF_BIRTH":"1996-04-20T00:00:00","GENDER":"Male","STAFF_ROLE":"Conductor","PHOTO":null},{new record..}]
There are several records here, I can't find a way to convert this json string to individual objects. I'm using the following to read in the data:
StringBuffer response;
try (BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()))) {
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
}
System.out.print(response.toString());
}
I've tried the simple json libary but the parser mixes up the string, Which is not ideal as I need to output the data to rows object by object to jtables.
Any help would be appreciated.
Solved it with the below with GSON. Many thanks everyone!
JsonElement jelement = new JsonParser().parse(response.toString());
JsonArray jarray = jelement.getAsJsonArray();
JsonObject jobject = jarray.get(0).getAsJsonObject();
System.out.println(jobject.get("FIRST_NAME"));
You can use something like this:
public class ObjectSerializer {
private static ObjectMapper objectMapper;
#Autowired
public ObjectSerializer(ObjectMapper objectMapper) {
ObjectSerializer.objectMapper = objectMapper;
}
public static <T> T getObject(Object obj, Class<T> class1) {
String jsonObj = "";
T userDto = null;
try {
jsonObj = objectMapper.writeValueAsString(obj);
userDto = (T) objectMapper.readValue(jsonObj, class1);
System.out.println(jsonObj);
} catch (JsonProcessingException jpe) {
} catch (IOException e) {
e.printStackTrace();
}
return userDto;
}
Pass your JSON Object to this method alogn with class name and it will set the JSON data to that respective class.
Note:
Class must have the same variables as in the JSON that you want to map with it.
Using org.json library:
JSONObject jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
see this
You can use Jackson to convert JSON to an object.Include the dependency :
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.3</version>
</dependency>
Then make a POJO class to store the JSON .The pojo class should reflect the json string structure and should have appropriate fields to map the values(Here in sample code Staff.class is a pojo class).Then, by using ObjectMapper class you can convert the JSON string to a java object as follows :
StringBuffer response;
try (BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()))) {
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
}
System.out.print(response.toString());
ObjectMapper mapper = new ObjectMapper();
//JSON from file to Object
Staff obj = mapper.readValue(new File("c:\\file.json"), Staff.class);
//JSON from String to Object
Staff obj = mapper.readValue(response.toString(), Staff.class);
Another simple method to read a JSON string and convert it into an object is :
JSON String:
{
"lastName":"Smith",
"address":{
"streetAddress":"21 2nd Street",
"city":"New York",
"state":"NY",
"postalCode":10021
},
"age":25,
"phoneNumbers":[
{
"type":"home", "number":"212 555-1234"
},
{
"type":"fax", "number":"212 555-1234"
}
],
"firstName":"John"
}
public class JSONReadExample
{
public static void main(String[] args) throws Exception
{
// parsing file "JSONExample.json"
Object obj = new JSONParser().parse(new FileReader("JSONExample.json"));
// typecasting obj to JSONObject
JSONObject jo = (JSONObject) obj;
// getting firstName and lastName
String firstName = (String) jo.get("firstName");
String lastName = (String) jo.get("lastName");
System.out.println(firstName);
System.out.println(lastName);
// getting age
long age = (long) jo.get("age");
System.out.println(age);
// getting address
Map address = ((Map)jo.get("address"));
// iterating address Map
Iterator<Map.Entry> itr1 = address.entrySet().iterator();
while (itr1.hasNext()) {
Map.Entry pair = itr1.next();
System.out.println(pair.getKey() + " : " + pair.getValue());
}
// getting phoneNumbers
JSONArray ja = (JSONArray) jo.get("phoneNumbers");
// iterating phoneNumbers
Iterator itr2 = ja.iterator();
while (itr2.hasNext())
{
itr1 = ((Map) itr2.next()).entrySet().iterator();
while (itr1.hasNext()) {
Map.Entry pair = itr1.next();
System.out.println(pair.getKey() + " : " + pair.getValue());
}
}
}
}
For reference:
https://www.geeksforgeeks.org/parse-json-java/
https://www.mkyong.com/java/jackson-2-convert-java-object-to-from-json/
What you have basically is this :
[
{
"TRAIN_JOURNEY_STAFF":[
],
"ID":15,
"EMAIL_ADDRESS":"jk#connectedrail.com",
"PASSWORD":"test",
"FIRST_NAME":"Joe",
"LAST_NAME":"Kevin",
"DATE_OF_BIRTH":"1996-04-20T00:00:00",
"GENDER":"Male",
"STAFF_ROLE":"Conductor",
"PHOTO":null
},
{
}
]
You can use JSON constructor to serialize this array to an Array of JSONObjects.
Try looking for JSONObject and JSONArray classes in Java.
The constructor basically takes the stringified JSON (which you already have).
I'm a .Net guy. I tried to call API and getting data from.
Serialized JSON object using java.. but I'm getting this error.
Expected BEGIN_ARRAY but was BEGIN_OBJECT
In .NET it's really easy to do. but in java, I haven't idea how to do that.
this my model class
public class Dictionary {
#SerializedName("metadata")
#Expose
private Metadata metadata;
#SerializedName("results")
#Expose
private List<Result> results = null;
public Metadata getMetadata() {
return metadata;
}
public void setMetadata(Metadata metadata) {
this.metadata = metadata;
}
public List<Result> getResults() {
return results;
}
public void setResults(List<Result> results) {
this.results = results;
}
}
And here the my api call
public class Oxford {
public String URL_OXFORD = "https://od-api.oxforddictionaries.com/api/v1/inflections/en/swimming";
public static List<Dictionary> httpGet(String url, String function) {
List<Dictionary> dataFromService = new ArrayList<Dictionary>();
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpGet request = new HttpGet(url+function);
request.addHeader("content-type", "application/json");
request.addHeader("app_id", "566566");
request.addHeader("app_key", "somekey");
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
com.google.gson.Gson gson = new com.google.gson.Gson();
Dictionary[] response = gson.fromJson(json, Dictionary[].class);
System.out.println(response.length);
for(Dictionary file : response)
{
dataFromService.add(file);
System.out.println(file.toString());
}
} catch (IOException ex) {
}
return dataFromService;
}
Since the documentation returns one object (starting with {, not a [) you probably need a
Dictionary response
instead of
Dictionary[] response
It is returning one dictionary object, not an array. Checkout the documentation at https://developer.oxforddictionaries.com/documentation
Please have a look at the below code snippet.
I had a look at some solutions provided on stackoverflow for adding String to a list.
They did not work out well in the below case.
#RequestMapping(value = "/rest/EmployeeDept/", method = RequestMethod.GET)
// ResponseEntity is meant to represent the entire HTTP response
public ResponseEntity<EmployeeDeptResponse> getDept()
{
EmployeeDeptResponse deptResponse = new EmployeeDeptResponse();
HttpStatus httpStatus;
List<EmployeeDept> employeeDeptList = new ArrayList<EmployeeDept>();
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(
"http://localhost:8082/rest/EmployeeDept/");
getRequest.addHeader("accept", "application/json");
HttpResponse response = httpClient.execute(getRequest);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
String output;
while ((output = br.readLine()) != null) {
employeeDeptList.add(output);
}
deptResponse.setItems(employeeDeptList);
httpClient.getConnectionManager().shutdown();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
httpStatus = HttpStatus.OK;
return new ResponseEntity<EmployeeDeptResponse>(deptResponse,httpStatus);
}
I am getting an error in the while loop as "add in list can not be applied to java.lang.String"
The list of type "EmployeeDept".The EmployeeDept class looks like this:-
package com.springboot.postrgres.model;
import java.io.Serializable;
public class EmployeeDept implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String dept;
public EmployeeDept() {
}
public EmployeeDept(int id, String dept) {
this.id = id;
this.dept = dept;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDept() {
return dept;
}
public void setDept(String name) {
this.dept = dept;
}
}
In the above code I have a list "employeeDeptList" and a string "Output".
I need to add this string to the list.
Can any of you provide suitable suggestions.
Thanks in advance.
employeeDeptList is of type ArrayList<EmployeeDept>.
List<EmployeeDept> employeeDeptList = new ArrayList<EmployeeDept>();
output on the other hand is of type String
String output;
So when you do employeeDeptList.add(output);, you are trying to add a String to your employeeDeptList, when it should be an EmployeeDept.
So you either make output an EmployeeDept or you rethink what you want to do with it.
As a suggestion, I am going to assume that your output should contain the information you need to create an EmployeeDept. You probably want to parse that information and create a EmployeeDept dept = new EmployeeDept(parsedId, parsedDept); and then add it to employeeDeptList as employeeDeptList.add(dept);
employeeDeptList is a list of EmployeeDept object. You are trying to add a String to the list of EmployeeDept. Which is not posssible unless you change the type of output variable to EmployeeDept.
If you response is a valid json (specified header), why won't you try to map it to objects?
ObjectMapper mapper = new ObjectMapper();
//assuming your response entity content is a list of objects (json array, since you specified header 'application/json'
String jsonArray = String theString = IOUtils.toString(response.getEntity().getContent(), encoding);
employeeDeptList = List<Employee> list = mapper.readValue(jsonString, TypeFactory.defaultInstance().constructCollectionType(List.class, employeeDeptList.class));
//assuming your response is a single object
String json = String theString = IOUtils.toString(response.getEntity().getContent(), encoding);
employeeDeptList.add(mapper.readValue(json, Employee.class));
//assuming every line of content is an object (does not really make sense)
BufferedReader br = new BufferedReader(ew InputStreamReader((response.getEntity().getContent())));
String output;
while ((output = br.readLine()) != null) {
employeeDeptList.add(mapper.readValue(output, Employee.class));
}
There is a problem in your code.
while ((output = br.readLine()) != null) {
employeeDeptList.add(output);
}
output is a String and you are trying to add that to a List<EmployeeDept>. You can't do that. If you want to add output to a List, you should create a List of Strings. Something like List<String>
As you mentioned, what you are getting is,
{
"1499921014230": {
"id": 1499921014230,
"dept": "mechanics"
},
"1499921019747": {
"id": 1499921019747,
"dept": "civil"
}
}
If you can change that , you can try to change it to a simple array of objects,
[
{
"id": 1499921014230,
"dept": "mechanics"
},
{
"id": 1499921019747,
"dept": "civil"
}
]
Add below dependency if you use maven, or just add the .jar to the lib,
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20090211</version>
</dependency>
Then try something like this,
while ((output = br.readLine()) != null) {
JSONArray jsonArr = new JSONArray(output);
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
String dept = jsonObj.getString("dept");
int id = jsonObj.getInt("id");
System.out.println("id : " + id + " dept : " + dept);
employeeDeptList.add(new EmployeeDept(id, dept));
}
}
Hi i am trying to iterate through a json string that looks like this:
{
"vendor":[
{
"vendor_name":"Tapan Moharana",
"vendor_description":"",
"vendor_slug":"tapan",
"vendor_logo":null,
"contact_number":null
}
],
"products":
{
"25":
{
"name":"Massage",
"price":"5000.0000",
"image":"http:\/\/carrottech.com\/lcart\/media\/catalog\/product\/cache\/1\/image\/150x\/9df78eab33525d08d6e5fb8d27136e95\/2\/9\/29660571-beauty-spa-woman-portrait-beautiful-girl-touching-her-face.jpg"
},
"26":
{
"name":"Chicken Chilly",
"price":"234.0000",
"image":"http:\/\/carrottech.com\/lcart\/media\/catalog\/product\/cache\/1\/image\/150x\/9df78eab33525d08d6e5fb8d27136e95\/c\/h\/cheicken.jpg"
},
"27":
{
"name":"Chicken Biryani",
"price":"500.0000",
"image":"http:\/\/carrottech.com\/lcart\/media\/catalog\/product\/cache\/1\/image\/150x\/9df78eab33525d08d6e5fb8d27136e95\/placeholder\/default\/image_1.jpg"
}
}
}
here is a better view of the json string:
I am iterating through the vendor array of this json string using this code:
JSONObject jsono = new JSONObject(response);
JSONArray children = jsono.getJSONArray("vendor");
for (int i = 0; i <children.length(); i++) {
JSONObject jsonData = children.getJSONObject(i);
System.out.print(jsonData.getString("vendor_name") + "<----");
// String vendorThumbNailURL=jsonData.getString("")
//jvendorImageURL.setImageUrl(local, mImageLoader);
vendorLogo=vendorLogo+jsonData.getString("vendor_logo").trim();
jvendorImageURL.setImageUrl(vendorLogo, mImageLoader);
jvendorName.setText(jsonData.getString("vendor_name"));
jvendorAbout.setText(jsonData.getString("vendor_description"));
jvendorContact.setText(jsonData.getString("contact_number"));
}
but I dont know how to get data from the "products" object please help me how do i set my json objects to iterate through "products"
when i try to change the format of the array so that both products and vendor are a separate json array i still get the above json format..
this is what i am doing
$resp_array['vendor'] = $info;
$resp_array['products'] = $vendorProductsInfo;
$resp_array = json_encode($resp_array);
print_r($resp_array);
please help me with this
MODIFIED QUESTION:
I have modified my web response like this:
[{"entity_id":24,"product_name":"Burger","product_image_url":"\/b\/u\/burger_large.jpg","price":"234.0000","category_id":59},{"entity_id":27,"product_name":"Chicken Biryani","product_image_url":"\/b\/i\/biryani.jpg","price":"500.0000","category_id":59},{"entity_id":31,"product_name":"Pizza","product_image_url":"\/p\/i\/pizza_png7143_1.png","price":"125.0000","category_id":59}]
and the code:
JSONArray children = jsono.getJSONArray("vendor");
for (int i = 0; i <children.length(); i++) {
JSONObject jsonData = children.getJSONObject(i);
System.out.print(jsonData.getString("vendor_name") + "<----");
// String vendorThumbNailURL=jsonData.getString("")
//jvendorImageURL.setImageUrl(local, mImageLoader);
vendorLogo=vendorLogo+jsonData.getString("vendor_logo").trim();
jvendorImageURL.setImageUrl(vendorLogo, mImageLoader);
jvendorName.setText(jsonData.getString("vendor_name"));
jvendorAbout.setText(jsonData.getString("vendor_description"));
jvendorContact.setText(jsonData.getString("contact_number"));
System.out.print(jsonData.getString("products") + "<----");
}
JSONObject jsono1 = new JSONObject(response);
JSONArray childrenProducts = jsono1.getJSONArray("products");
for(int i=0;i<childrenProducts.length();i++){
JSONObject jsonData = childrenProducts.getJSONObject(i);
System.out.print(jsonData.getString("name") + "<----dd");
}
but still the products part is not working... please help
Here is the working solution: Using GOOGLE GSON (Open source jar)
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class JsonToJava {
public static void main(String[] args) throws IOException {
try{
String json = "<YOUR_JSON>";
Gson gson = new GsonBuilder().create();
VendorInfo vInfo = gson.fromJson(json, VendorInfo.class);
System.out.println(vInfo.getVendorName());
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
Create classes for Vendor and Product
public class Vendor {
public String vendor_name;
public String vendor_description;
public String vendor_slug;
public String vendor_logo;
public String contact_number;
public String getName() {
return vendor_name;
}
}
public class Product {
public String name;
public long price;
public String image;
public String getName() {
return name;
}
}
VendorInfo is the JSON object form:
import java.util.Map;
public class VendorInfo {
public Vendor[] vendor;
public Map<Integer, Product> products;
public String getVendorName() {
return vendor[0].getName();
}
public Product getProduct() {
System.out.println(products.size());
return products.get(25);
}
}
You can add your getters for Vendor, Product and VendorInfo. You are done! You will get all the data.
Output of JsonToJava:
Tapan Moharana
To get your products data , you need to use Iterator
JSONObject jProducts = jsonObject
.optJSONObject("products");
try {
if (jProducts
.length() > 0) {
Iterator<String> p_keys = jProducts
.keys();
while (p_keys
.hasNext()) {
String keyProduct = p_keys
.next();
JSONObject jP = jProducts
.optJSONObject(keyProduct);
if (jP != null) {
Log.e("Products",
jP.toString());
}
}
}
} catch (Exception e) { // TODO:
// handle
// exception
}
you can try with this
JSONObject jsono = null;
try {
jsono = new JSONObject(response);
JSONObject productObject = jsono.getJSONObject("products");
Iterator<String> keys = productObject.keys();
while (keys.hasNext())
{
// get the key
String key = keys.next();
// get the value
JSONObject value = productObject.getJSONObject(key);
//get seprate objects
String name = value.getString("name");
String image = value.getString("image");
Log.i(TAG,name+"-"+image);
}
}
catch (JSONException e) {
e.printStackTrace();
}
Try this :
JSONObject productObject = jsono.getJSONObject("products");
JSONObject json_25 = productObject getJSONObject("25");
String name_25= json_25.getString("name");
String price_25= json_25.getString("price");
String image_25= json_25.getString("image");
JSONObject json_26 = productObject getJSONObject("26");
String name_26= json_26.getString("name");
String price_26= json_26.getString("price");
String image_26= json_26.getString("image");
JSONObject json_27 = productObject getJSONObject("27");
String name_27= json_27.getString("name");
String price_27= json_27.getString("price");
String image_27= json_27.getString("image");