How to send nested json as post in android - java

im using android valley library, currently im only able to post simple json, im struggling in posting nested json format like this :
{
"user": {
"email": "digest#example.com",
"password": "thedigest123"
it looks like i didnt know how to format the nested json for this case, could you help me?
here's my java class that i used to connect my web api
public void login(String email, String password) {
String url = BASE_URL + "api/session";
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("email", email);
jsonObject.put("password", password);
Response.Listener<JSONObject> successListener = new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(mApplication, "Success", Toast.LENGTH_SHORT).show();
}
};
Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(mApplication, "Error", Toast.LENGTH_SHORT).show();
}
};
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, jsonObject, successListener, errorListener);
mRequestQueue.add(request);
}
catch (JSONException e) {
Toast.makeText(mApplication, "JSON exception", Toast.LENGTH_SHORT).show();
}
}

Create dto classes for your request body:
public class UserRequestDTO{
private UserDto user;
//getters, setters
}
public class UserDto{
private String email;
private String password;
}
Convert it to json string using Gson lib:
public static String stringify(Object obj) {
Gson gson = new Gson();
String jsonString = gson.toJson(obj);
return jsonString;
}
Then convert it to StringEntity with new StringEntity(stringify(new UserRequestDto(/*params*/), "UTF-8");
or to JSONObject with new JSONObject(stringify(new UserRequestDto(/*params*/));, and use it in your request.

If you don't want the overhead of Gson or creating classes (unless you intend to have more complex objects) You can simply do:
JSONObject userJsonObject = new JSONObject("{ \"user\": {\"email\": \"" + email + "\", \"password\": \"" + password + "\" } }");

Related

JSONObject cannot be converted to String

I saw this questions a bunch of times here in Stack, but had no luck. The thing is, I'm using this API for validate my CNPJ field, if I have a connection, the response would be the field "nome" and populate my textview field.
So far so good, the JSON is valid (already passed in jsonformatter) but I can't the object through JSONArray and when I manage to find it by JSONObject it tells me that can't be converted to String.
valide.setOnClickListener(view1 -> {
//String PJ = cnpj.getText().toString();
String PJ = "06990590000123";
String url = "https://www.receitaws.com.br/v1/cnpj/" + PJ;
jsonParse(url);
});
private void jsonParse(String url) {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
String json;
#Override
public void onResponse(JSONObject response) {
try {
json = response.getJSONObject("nome").toString();
razao.append(json);
razao.setText(json);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Invalid ! ", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError erro) {
erro.printStackTrace();
}
});
mQueue.add(request); //Volley.newRequestQueue
}
JSON
{ "atividade_principal": [ { "text": "Portais, provedores de conteúdo e outros serviços de informação na internet", "code": "63.19-4-00" } ],
"data_situacao": "01/09/2004",
"complemento": "ANDAR 17A20 TSUL 2 17A20", "tipo": "MATRIZ",
**"nome": "GOOGLE BRASIL INTERNET LTDA.", //Need this field**
"uf": "SP",
"telefone": "(11) 2395-8400",
"email": "googlebrasil#google.com",
LOG
org.json.JSONException: Value GOOGLE BRASIL INTERNET LTDA. at nome of
type java.lang.String cannot be converted to JSONObject
at org.json.JSON.typeMismatch(JSON.java:101)
URL USED
https://www.receitaws.com.br/v1/cnpj/06990590000123
Can someone help me with this problem, please ? Thank you !
In your JSON the nome is of type String. So rather than getJSONObject use getString method from JSONObject class. So your code should be like below:
private void jsonParse(String url) {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
String json;
#Override
public void onResponse(JSONObject response) {
try {
json = response.getString("nome"); // Here is the change
razao.append(json);
razao.setText(json);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Invalid ! ", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError erro) {
erro.printStackTrace();
}
});
mQueue.add(request); //Volley.newRequestQueue
}
Try this:
First construct JsonObject and then get the string value of the key.
JSONObject jsonObject = new JSONObject(json);
String valueIWanted = jsonObject.getString("nome"))

How to use gson for getstring of json?

I am new to use gson.
I found a lots of tutorial there I can learn of gson but there are using recylerview and model file.
JsonObjectRequest request = new JsonObjectRequest(LoginUrl, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG , String.valueOf(response));
try {
String statusObject = response.getString("status");
String msgObject = response.getString("msg");
if (statusObject.equals("200")) {
JSONArray jsonArray = response.getJSONArray("response");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject managerResponse= jsonArray.getJSONObject(i);
// userIdObject = managerResponse.getString("user_id");
// String nameObject = managerResponse.getString("name");
// String emailObject = managerResponse.getString("email");
// String mobileObject = managerResponse.getString("mobile");
// String postobject = managerResponse.getString("post");
// pojectObject = managerResponse.getString("project");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
}
Here I can get data from jsonrequest using volley but unable to do that same process using volley and gson. Is there any way to use gson?
Thank You.
Update
My JSON Response
{
"status": "200",
"msg": "Successfully",
"response": [
{
"user_id": "1",
"name": "HEMANT OJHA",
"email": "hemguna#gmail.com",
"mobile": "9584919991",
"address1": "C92, PALLAWI NAGAR BABADIYA KALAN",
"user": "admin",
"api_token": "admin"
}
]
}
Generating POJO class from JSON
// Considering your response consists of json objects & json array
// Create a POJO class for your response with the link above
{
"keyOne": 1,
"keyTwo": "Some Value",
"someArray": [{
"key": "Value"
},
{
"key": "Value"
}
]
}
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class ExampleClass {
#SerializedName("keyOne")
#Expose
private int keyOne;
#SerializedName("keyTwo")
#Expose
private String keyTwo;
#SerializedName("someArray")
#Expose
private List<SomeArray> someArray = null;
public int getKeyOne() {
return keyOne;
}
public void setKeyOne(int keyOne) {
this.keyOne = keyOne;
}
public String getKeyTwo() {
return keyTwo;
}
public void setKeyTwo(String keyTwo) {
this.keyTwo = keyTwo;
}
public List<SomeArray> getSomeArray() {
return someArray;
}
public void setSomeArray(List<SomeArray> someArray) {
this.someArray = someArray;
}
}
// Parsing JSON response with GSON
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
ExampleClass resultObj = gson.fromJson(jsonObject.toString(), ExampleClass.class);
int keyOneValue = resultObj.getKeyOne() // First JSON Object
// Getting String value
String keyTwoValue = resultObj.getKeyTwo() // Second JSON Object
List<SomeArray> yourJSONArray = resultObj.getSomeArray() // Getting JSON Array contents
// Depending on JSON response that you've updated in your question
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
ExampleClass resultObj = gson.fromJson(jsonObject.toString(),ExampleClass.class);
String status = resultObj.getStatus();
String msg = resultObj.getMsg();
List<Response> responseList = resultObj.getResponse();
The best way to use for entire app is create a Utils class and use it for conversion.
GsonUtils.java
// This Class is useful for mapping Json into Java Objects and vice versa.
public class GsonUtils {
private static final Gson gson = new Gson();
// This will Convert Java Objects into JSON String...
public static String toGson(Object object) {
return gson.toJson(object);
}
// Gives Java Objects from JSON
public static <T> T fromGson(String json, Class<T> type) {
return gson.fromJson(json, type);
}
public static JsonArray fromGson(String json) {
return new JsonParser().parse(json).getAsJsonArray();
}
}
Now convert any json to and from POJO via,
POJO pojoObj = GsonUtils.toGson(POJO.class);
Try this
JSON response
String str = new Gson().toJson(response)

How to solve: org.json.JSONException: Value GVL7TY of type java.lang.String cannot be converted to JSONObject

I'm trying to make a post request and get a string that my server generates as a response. I get this error: D/Error.Response: com.android.volley.ParseError: org.json.JSONException: Value GVL7TY of type java.lang.String cannot be converted to JSONObject. the GVL7TY value is the generated code from the server. I'm new to android and I don't know how to fix it. appreciate your help!
private void sendRequest(final String email, final String name,String url,RequestQueue queue) {
JSONObject request = new JSONObject();
try
{
request.put("TeacherEmail", email);
request.put("ClassName", name);
}
catch(Exception e)
{
e.printStackTrace();
}
JsonObjectRequest postRequest = new JsonObjectRequest(Request.Method.POST, url, request,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject responseObj) {
// response
Log.d("Response", responseObj.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
}
) {
};
queue.add(postRequest);
}
The response returned from your server is not valid json. Try debuging the raw response.

Parsing JsonObjectRequest

I am new to Android and JAVA and I am trying to parse a json response. I know how to parse jsonarray but no Idea how to parse jsonobject. Can someone tell me how? Below is my Response.
{"118":{"garment_color":"Blue","garment_name":"skjhkds","garment_price":"232"},"119":{"garment_color":"hjsadjjs","garment_name":"sdasd","garment_price":"23478"}}
And this is how parsed jsonarray.
public void JSON_DATA_WEB_CALL(){
jsonArrayRequest = new JsonArrayRequest(GET_JSON_DATA_HTTP_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
progressBar.setVisibility(View.INVISIBLE);
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImageTitleNamee(json.getString(JSON_IMAGE_TITLE_NAME));
//GetDataAdapter2.setImageServerLarger(json.getString(JSON_IMAGE_LARGER));
GetDataAdapter2.setImageServerUrl(json.getString(JSON_IMAGE_URL));
GetDataAdapter2.setMrp_price(json.getString(JSON_MRP_PRICE));
GetDataAdapter2.setDisc_price(json.getString(JSON_DISC_PRICE));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, this);
recyclerView.setAdapter(recyclerViewadapter);
}
Please Someone help. Thanks.
In my opinion, use Gson library, where you give it the json object/array/string and it automatically parses it into a java object. Note that you have to define the java class with the appropriate fields.
EDIT: So here's an answer that goes with the suggested guidelines:
First create your model classes just like you will receive them from the server:
public class MyServerObject {
MyGarment jsonKeyName;
}
public class MyGarment {
String garment_color;
String garment_name;
String garment_price;
}
Next, after receiving your json string, parse it using Gson:
Gson gson = new Gson();
String json= "{"jsonKeyName":{"garment_color":"Blue","garment_name":"skjhkds","garment_price":"232"};
MyServerObject serverObject = gson.fromJson(json, MyServerObject.class);
Now, you can access your Garment object from your server object with all the values parsed correctly. Also note that if you're receiving a json array you could add the object as a list in your MyServerObject.class.
Hope this helps.
as per my above comment
you need to make JSONObject request instead of JSONArray request
try this to parse your JSON Response
try {
JSONObject jsonObject= new JSONObject("Response");
JSONObject jsonObject1=jsonObject.getJSONObject("118");
String garment_color=jsonObject1.getString("garment_color");
String garment_name=jsonObject1.getString("garment_name");
String garment_price=jsonObject1.getString("garment_price");
JSONObject jsonObject2=jsonObject.getJSONObject("119");
String garment_color2=jsonObject1.getString("garment_color");
String garment_name2=jsonObject1.getString("garment_name");
String garment_price2=jsonObject1.getString("garment_price");
} catch (JSONException e) {
e.printStackTrace();
}
Use StringRequest instead of JSONObject/JSONArray request and finally fetch value like this:
JSONObject object = new JSONObject(YOUR JSON RESPONSE);
String s1 = object.getJSONObject("118").getString("garment_color");

Receive & Output JSON Error Message Android

I have created an API for the purpose to retrieve data from database. Now I able to retrieve status, message and data from the API no matter I input the credentials correct or incorrect. There are two version of output. I used POSTMan to test on and that it seems working but when I try on Android, success message is okay but not the error one.
#POST
#Path("/appdatas")
public Response getSAppData(AppDataRequest adr) {
Response data = ads.getSAppData(adr.getId(), adr.getEmail(), adr.getPassword());
return data;
}
#SuppressWarnings("unchecked")
public Response getSAppData(int id, String email, String password){
Map<String, AppData> AppDataHM = new HashMap<String, AppData>();
Map<String, Data> DataHM1 = new HashMap<String, Data>();
Map<String, List<String>> DataHM2 = new HashMap<String, List<String>>();
Map ADHMDHM = new HashMap<>();
Data data = DataHM.get(new AppDataRequest (id, email, password));
List<String> message = new ArrayList<>();
List<String> data2 = new ArrayList<>();
if(data != null){
message.add("");
AppDataHM.put("AppData", new AppData("success", message));
DataHM1.put("Data", data);
ADHMDHM.putAll(AppDataHM);
ADHMDHM.putAll(DataHM1);
String ADHMDHM1 = new Gson().toJson(ADHMDHM);
return Response.status(200).entity(ADHMDHM1).build();
}
else{
message.add("Your login information is invalid. Please try with the correct information");
AppDataHM.put("AppData", new AppData("error", message));
DataHM2.put("Data", data2);
ADHMDHM.putAll(AppDataHM);
ADHMDHM.putAll(DataHM2);
String ADHMDHM2 = new Gson().toJson(ADHMDHM);
return Response.status(500).entity(ADHMDHM2).build();
}
}
When I use POSTMan, I able to retrieve both output.
{
"AppData": {
"status": "success",
"message": [
""
]
},
"Data": {
"token": "token1"
}
}
{
"AppData": {
"status": "error",
"message": [
"Your login information is invalid. Please try with the correct information"
]
},
"Data": []
}
When I apply the following code on Android, I able to retrieve data for success one but not the error one.
private void makeJsonObjectRequest(){
showpDialog();
String id1 = mEditTextID.getText().toString();
String email1 = mEditTextEmail.getText().toString().trim();
String password1 = mEditTextPassword.getText().toString();
HashMap<String, String> params = new HashMap<String, String>();
params.put("id", id1);
params.put("email", email1);
params.put("password", password1);
JsonObjectRequest request = new JsonObjectRequest(url, new JSONObject(params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject AppData = response.getJSONObject("AppData");
String status = AppData.getString("status");
String message = AppData.getString("message");
//JSONObject Data = response.getJSONObject("Data");
//String token = Data.getString("token");
jsonResponse = "";
jsonResponse += "Status: " + status + "\n";
jsonResponse += "\n";
jsonResponse += "Message: " + message + "\n";
//jsonResponse += "\n";
//jsonResponse += "Token: " + token + "\n";
mTextViewMain.setText(jsonResponse);
hidepDialog();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(),
"Error: " + e.getMessage(),
Toast.LENGTH_SHORT).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error1: " + error.getMessage());
Toast.makeText(getActivity(),
"Error2: " + error.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
});
AppController.getInstance().addToRequestQueue(request);
}
How possible I can get the output as shown in the 'error' output and display in the TextView?
Thanks for everyone for viewing this question.
Why are you returning status 500 in your script? Volley assumes code 500 as error
return Response.status(500).entity(ADHMDHM2).build();
Try changing it to 200 and check
You can use this link to generate concrete classes for the json. Once you have the concrete classes then you can use GSON to convert json text to class. This way you will have concrete json to class mapping.
May be this can help.
For Message try this:
JSONArray messageArray = AppData.getJSONArray("message");
String message = messageArray.toString();

Categories