I have the JSON Array below, created by a JPA function on a WebService:
[{"Producao":{"cliente":{"id":3,"nome_fantasia":"animal"},"data":"2013-11-08T00:00:00-02:00","id":1,"liberado":0,"prazo":"2013-11-14T00:00:00-02:00","produto":{"codigo_desenho":"CODIGO","dependencia":0,"descricao":"Produto1","disponivel":1,"id":39,"qtde":1,"raiz":0},"qtde":1}},{"Producao":{"cliente":{"id":1,"nome_fantasia":"bem"},"data":"2013-11-08T00:00:00-02:00","id":2,"liberado":0,"prazo":"2013-11-14T00:00:00-02:00","produto":{"codigo_desenho":"","dependencia":0,"descricao":"teste3","disponivel":1,"id":35,"qtde":1,"raiz":0},"qtde":2}}]
And I have to read it in my Android App. Converting them to a List.
The Object "Producao" has the Object "Cliente" as attribute.
I'm trying to do as below:
public static Producao jSONToProducao(JSONObject json) throws JSONException, ParseException{
JSONObject jPro = json.getJSONObject("Producao");
Producao producao = new Producao();
producao.setId(jPro.getInt("id"));
producao.setCliente(ClienteDAO.jSONToCliente(jPro.getJSONObject("cliente")));
.
.
.
return producao;
}
Where ClienteDAO.jSONToClient is:
public static Cliente jSONToCliente(JSONObject json) throws JSONException{
JSONObject jCli = json.getJSONObject("Cliente");
Cliente cliente = new Cliente();
cliente.setId(jCli.getInt("id"));
cliente.setNome_fantasia(jCli.getString("nome_fantasia"));
return cliente;
}
but the line producao.setCliente(ClienteDAO.jSONToCliente(jPro.getJSONObject("cliente"))) returns:
JSON Exception ~> No value for cliente”. ¬¬'
I tried to read it as a JSONArray too, but it didn't work.
JSON Exception ~> No value for cliente
because you are passing cliente JSONObject to jSONToCliente method from jSONToProducao so change your code as to get all values from cliente JSONObject :
public static Cliente jSONToCliente(JSONObject json) throws JSONException{
// json contain only cliente JSONObject
Cliente cliente = new Cliente();
cliente.setId(json.getInt("id"));
cliente.setNome_fantasia(json.getString("nome_fantasia"));
return cliente;
}
Related
I am developing a rest server in java, netbeans.
I have my GET request:
//myip/application/v1/cardapio/id=1
#Stateless
#Path("v1/cardapio")
public class CardapioResource {
#GET
#Produces("application/json")
#Path("id={id}")
public String getCardapio(#PathParam("id") int id) {
JsonArray array = (JsonArray) gson.toJsonTree(ejb.findById(id));
JsonObject obj = new JsonObject();
obj.add("dados", array);
return obj.toString();
}
}
It works correctly.
But I want to do differently, as I saw in other examples, I want to mark the beginning of the variables with the "?".
Ex: //myip/application/v1/cardapio/?id=1
#Stateless
#Path("v1/cardapio")
public class CardapioResource {
#GET
#Produces("application/json")
#Path("?id={id}")
public String getCardapio(#PathParam("id") int id) {
JsonArray array = (JsonArray) gson.toJsonTree(ejb.findById(id));
JsonObject obj = new JsonObject();
obj.add("dados", array);
return obj.toString();
}
}
Thus error 404, page not found.
What you seen in "other examples" is just normal usage of URL's query part. Just use it with #Queryparam
#Stateless
#Path("v1/cardapio")
public class CardapioResource {
#GET
#Produces("application/json")
#Path("/") // can be removed actually
public String getCardapio(#QueryParam("id") int id) {
JsonArray array = (JsonArray) gson.toJsonTree(ejb.findById(id));
JsonObject obj = new JsonObject();
obj.add("dados", array);
return obj.toString();
}
}
Here you are mapping getCardapio to v1/cardapio/ and you will try to get id from query string so
Ex: //myip/application/v1/cardapio/?id=1
will just work.
You can't, after ? sign it's query parameters and not path parameters
You can use #QueryParam("id")
You can also use
#RequestParam("id") int id
I'm trying to Parse very simply JSON to object (with GSON)
My JSON:
[{"username":"admin","password":"admin","name":"admin","email":"admin#admin.com"},{"username":"mark20","password":"mark123","name":"mark","email":"mark#steew.com"}]
is there 2 users, so I create 2 class, Users with list of users and User :
public class Users {
ArrayList<User> users;
Users(ArrayList<User> users){
this.users = users;
}
}
.
public class User {
String userame;
String password;
String name;
String email;
}
and here is my parsing code:
public void onResponse(Call call, Response response) throws IOException {
String body = response.body().string();
Gson gson = new GsonBuilder().create();
Users users = gson.fromJson(body, Users.class);
}
of course in variable body I have got correct JSON, but in last lane I got:
JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY
What can be wrong here ? How to fix it ?
Your json is an array of User not a wrapper Users of array User.
Read your json like this:
User[] users = gson.fromJson(body, User[].class);
If you want an ArrayList<>:
List<User> userList = Arrays.asList(users);
Another way is to use TypeToken:
Type listType = new TypeToken<ArrayList<User>>(){}.getType();
List<User> userList = gson.fromJson(body, listType);
If I'm reading from what I read elsewhere correctly try:
public void onResponse(Call call, Response response) throws IOException {
String body = response.body().string();
Gson gson = new GsonBuilder().create();
User[] users = gson.fromJson(body, User[].class);
}
I made the first request successfully and I like to access my Volley response in other class , how can I do that because when I try to do that it return a null response
use interface and callback
public interface RestCallBack {
void onStart(String action);
void onComplete(String response, String action,Exception e);
}
And in your onResponse
listener.onComplete(response, action, null);
Then you can implement this interface in any class where you want the response.
At first its depends on your json data formate .......
You need to create a class
Declare a method in your class with a parameter string or array and call this method where you get json response
or follow this code
public class MyJsonParser {
public static Vector<MyModel> getJsonResponse(Context context,String response)
throws JSONException, IOException
{
final JSONObject stringResponse = new JSONObject(response);
final JSONObject responseHolder = stringResponse.getJSONObject("data");
final JSONArray jsonArray = responseHolder .getJSONArray("arrayData");
MyModel myModel;
Vector<MyModel> myArray = new Vector<MyModel>();
for (int i= 0;i<jsonArray .length();i++){
myModel= new MyModel();
JSONObject propertyHolder = jsonArray .getJSONObject(i);
myModel.setId(propertyHolder,"id");
myModel.setName(propertyHolder, "name");
myArray .addElement(myModel);
myModel= null;
}
return myArray ;
}
}
and call this method where you get json response like this....
MyJsonParser.getJsonResponse(context,response);
I am trying to send following Integer value to server.
int mStoreArea;
I use this link as REST client.
here is Request:
RestClient client = new RestClient(my_url);
client.AddParam("area", String.valueOf(c.getStoreArea()));
and the Error I face is : Int value required!
I retrieve this integer from a json object saved to a file, its procedure is described below:
public myClass(JSONObject json) throws JSONException {
mStoreArea = json.optInt(JSON_TAG);
}
public JSONObject toJSON() throws JSONException {
JSONObject json = new JSONObject();
json.put(JSON_TAG, mStoreArea);
return json;
}
I think you should use this:
client.AddParam("area", Integer.parseInt(c.getStoreArea()));
#GET
#Produces(MediaType.APPLICATION_JSON)
public List<ProductData> getAllProductList(#QueryParam("hotel_id") int hotel_id) throws SQLException{
System.out.println("Hotel id id==="+hotel_id);
ProductData productData=new ProductData();
List<ProductData> products = new ArrayList<ProductData>();
rs=stmt.executeQuery("select * from products where hotel_id="+hotel_id);
while(rs.next()){
productData.setProductName(rs.getString("name"));
productData.setProductCategory(rs.getString("category"));
productData.setProductRate(rs.getDouble("rate"));
productData.setProductLogoPath(rs.getString("productLogoPath"));
products.add(productData);
}
return products;
}
I have passed List as JsonObject.Now i tried to get List value like
void handleResponse(String response) throws JSONException {
JSONObject jsonObject=new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("products");
}
but i can't get the List value.anyBody can help me?
There is the simple way to convert json string to object :
Try this :
ObjectMapper mapper = new ObjectMapper();
POJO obj = mapper.readValue(yourJSONString, POJO.class);
Use method signature something similar like-
public Response getAllProduct..
&
return like-
return Response.status(Status.OK).entity(products).build();
For intg. layer use-
public ClientResponse<> similarSignatureMethod..
&
call via the client and then get response entity as-
clientResponse.getEntity();