i'm posting some data to a web service and i'm getting a json reply which i want to pass to a jsonobject.
The reply of the web service is:
{
"ValidateLoginResult": [
{
"ErrorMessage": "Wrong username pass",
"PropertyName": null
}
]
}
and i want to pass the error message and the property name to variables. I tried using JSONobject and JSONarray but didnt have any luck
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(serverURL);
StringEntity se = new StringEntity(data);
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. Getting Reply
inputStream = httpResponse.getEntity().getContent();
...
...
JSONArray json = new JSONArray(convertInputStreamToString(inputStream));
JSONObject json_LL = json.getJSONObject(0);
String str_value=json_LL.getString("ErrorMessage");
You are getting response in JSONObject and you are trying to get it in JSONArray.. thats why you are getting error..
Try this way...
try {
JSONObject result = new JSONObject(response);
if(data.has("ValidateLoginResult"){
JSONArray array = result.getJSONArray("ValidateLoginResult");
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
String ErrorMessage= ""+obj.getString("ErrorMessage");
String PropertyName= ""+obj.getString("PropertyName");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
OR
if you want one line answer..Try this..
// going directly to array object..
JSONObject result = new JSONObject(response).getJSONArray("ValidateLoginResult").getJSONObject(0);
String ErrorMessage= ""+result.getString("ErrorMessage");
String PropertyName= ""+result.getString("PropertyName");
Related
I am trying to create a playlist using the Spotify API, and I am writing the POST request to the Spotify API endpoint in Java. I have also included every available scope from Spotify when I retrieve my access token. This is returning a response with an error message of:
{"error":{"message":"Error parsing JSON.","status":400}}
Here is what I have:
String http = "https://api.spotify.com/v1/users/" + userId + "/playlists";
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(http);
JsonObject entityObj = new JsonObject();
JsonObject dataObj = new JsonObject();
dataObj.addProperty("name", "title");
dataObj.addProperty("public", "false");
entityObj.add("data", dataObj);
String dataStringify = GSON.toJson(entityObj);
StringEntity entity = new StringEntity(dataStringify);
post.setEntity(entity);
post.setHeader("Authorization", "Bearer " + accessToken);
post.setHeader("Content-Type", "application/json");
CloseableHttpResponse response = client.execute(post);
System.out
.println("Response Code : " + response.getStatusLine().getStatusCode());
String resp = EntityUtils.toString(response.getEntity());
JSONObject responseObj = new JSONObject(resp);
System.out.println(responseObj);
client.close();
Please let me know if you have any insights into what is wrong.
I am assuming you are using the org.json library as well as Google's Gson library. Using both doesn't make sense in this context. You won't need
String dataStringify = GSON.toJson(entityObj);
as entity Object already is a JSON Object. entityObj.toString() should be enough.
The current JSON Data you are sending looks like this:
{
"data":
{
"name":"title",
"public":"false"
}
}
Spotify ask for an JSON Object like this:
{
"name": "New Playlist",
"public": false
}
You only have to send the Data Object dataObj.
I have written a web-service in Java. This web-service is hosted in TOMCAT. I am returning a JSON string. The JSON string is as follows:
accountDetailsNodes = [{mobileNumber=01948330292, errorMessage=null, customerCode=59744000002, photo=a string of 35536 charaters , accountOpenDate=null, errorFlag=N, customerNumber=4, customerName=Md. Saifur Hossain , accountID=2, accountTypeId=13, accountTypeDescription=Savings Account, customerPointId=1, balance=100000037640.50, accountTile=Md. Saifur Hossain}]
The length of the JSON string is 32613. But the full response is not coming to android apps. I think there may be some limitation on sending response from Tomcat. How can I overcome this limitation of Tomcat?
Updated:
This is my code to generate JSON.
try {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
JSONObject json = new JSONObject();
CashDepositDao dao = new CashDepositDao();
for (CashDepositModel bo : dao.getAccountDetals(accountNo,branchCode)) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("accountTile", bo.getAccountTitle());
map.put("accountOpenDate", bo.getAccountOpenDate());
map.put("mobileNumber", bo.getMobileNumber());
map.put("balance", bo.getBalance());
map.put("accountTypeId", bo.getAccountTypeID());
map.put("accountTypeDescription", bo.getAccountTypeDescription());
map.put("accountID", bo.getAccountID());
map.put("customerNumber", bo.getCustomerNumber());
map.put("customerCode", bo.getCustomerCode());
map.put("customerName", bo.getCustomerName());
map.put("customerPointId", bo.getCustomerPointID());
map.put("photo", bo.getPhoto());
map.put("errorMessage", bo.getErrorMessage());
map.put("errorFlag", bo.getErrorFlage());
list.add(map);
json.put("accountDetailsNodes", list);
}
System.out.println("accountDetailsNodes = " + list);
response.addHeader("Access-Control-Allow-Origin", "*");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().print(json.toString());
response.getWriter().flush();
// System.out.println("Response Completed... ");
} catch (Exception ex) {
Logger.getLogger(SourecAccountDetailsSV.class.getName()).log(Level.SEVERE, null, ex);
}
Sending And Getting response from Mobile App:
I am sending and getting the response using the following code:
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
System.out.println(json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
I have printed the string received in this method . Surprisingly, the full string is not received in this method.
How can I overcome this limitation of tomcat ?
Tomcat can send arbitrary length strings, and even if there was a limit, it wouldn't be measured in kilobytes but in orders of magnitude more. There is no tomcat limitation that you need to overcome. If your browser receives the full string, so can any other app.
As you're using json.toString() anyways, you could explicitly set the Content-Length header and see if this makes a difference. Stop worrying about Tomcat and double check if your Android App has some problems parsing a json response of this size, or if any network component in between limits your response in some way.
Edit: It's not Tomcat's problem, it's on the Android side and your answer is in the comments to the question.
The first problem is in what's proposed as "duplicate" question: You must not compare String with == as you do. Add else System.out.print("unexpected"); to your first if/else block to illustrate.
The second problem is that we have no clue where you get is from. As it looks now, it could be overridden by parallel requests (it's probably a class member?) - or due to the wrong string comparison never be initialized at all (leading to your problem that you can't see any content at all on the Android side, despite tomcat sending it). Make it a local variable, as proposed by EJP in his/her comment.
I think there may be some limitation on sending response from Tomcat.
There isn't.
How can I overcome this limitation of Tomcat?
There is no such limitation.
I am sending and getting the response using the following code:
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
Here you are incorrectly comparing strings. You should use equals(), not ==.
// ...
}else if(method == "GET"){
Ditto.
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
Here you are using is which may not have been initialized at all. It appears to be a member variable, so it is probably still null, so at this point I would expect a NullPointerException. is should of course be a local variable in this method.
I have printed the string received in this method. Surprisingly, the full string is not received in this method.
What is surprising is that anything is received, if that's what you're claiming. I would have expected an NPE.
I need to send a list of byte[] as json parameter to .net(wcf) server. Is it possible? or should I do base64 encoding and proceed?
For example, I need to pass a sessionId(String) and datalist(ArrayList<byte[]>) in a json object. I am using Retrofit Library, creating request model POJO and sending. sessionId is recieved in the server, but for 'datalist', server is recieving null.
Thanks in Advance
Try this code, this is how to send JSON data to restful web service:
JSONArray jsonArray=new JSONArray();
ArrayList<byte[]>arrayList=new ArrayList<byte[]>();
Iterator<byte[]> itr=arrayList.iterator();
while (itr.hasNext()) {
byte[] bs = (byte[]) itr.next();
JSONObject temp=new JSONObject();
temp.put("byte",bs.toString());
jsonArray.put(temp);
}
// create HttpClient
HttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
StringEntity se = new StringEntity(jsonArray.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
HttpResponse response = httpclient.execute(post);
InputStream inputStream = response.getEntity().getContent();
// convert inputstream to string
I tried the code in android below:-
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://echo.jsontest.com/key/value/one/two");
String text = null;
try {
HttpResponse response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
JSONArray jsonObj = new JSONArray(entity);
System.out.print("message is"+jsonObj);
}
catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
//Below i am displaying in my layout in my emulator
protected void onPostExecute(String results) {
if (results!=null) {
TextView et = (TextView)findViewById(R.id.data);
et.setText(results);
}
Button b = (Button)findViewById(R.id.getvehicles);
b.setClickable(true);
}
so when i just use getASCIIContentFromEntity(entity) ,then i am able to print full JSON data as it is.but instead i wanna print only the values inside this URL it is JSON data,please open to see it .
How can i fetch the values inside this json URL?
Your response is in a JSONObject form so you have to get it like this.
HttpResponse response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
Object content = EntityUtils.toString(entity);
JSONObject jsonObj = new JSONObject(content.toString());
System.out.print("message is"+jsonObj.toString());
Then your JSONObject contains multiple values, you can get it by using the "key" of the pair.
String value = jsonObj.getString(key); //String value = jsonObj.getString("one");
In your case you want to print one and two, which means the kay and value, so you have to iterate the entire collection like this(If you know the keys used in the response no need of using this method).
Iterator<?> keys = jsonObj.keys();
while( keys.hasNext() ){
String key = (String)keys.next();
System.out.print("key - value"+ key + jsonObj.getString(key));
}
I need to send json array as a paramater via post method from android ...and receive jsonarray as response..
what should be the conversion of below mentioned request in java..??
curl -H "X-OpenSRF-service: open-ils.search" --data 'osrf-msg=[{"__p" : {"threadTrace" : 0, "payload" : { "__c" : "osrfMethod","__p" : { "params" :"30007004981493","method" : "open-ils.search.biblio.find_by_barcode"}},"type" : "REQUEST","locale" : "en-US"},"__c" : "osrfMessage"} ]' http://localhost/osrf-http-translator
i have done it like this..
HttpParams httpParams = new BasicHttpParams();
HttpClient client = new DefaultHttpClient(httpParams);
HttpPost httpost = new HttpPost("http://"+hostname+"/osrf-http-translator");
// httpost.setHeader("Accept", "application/json");
// httpost.setHeader("Content-type", "application/json");
httpost.setHeader("X-OpenSRF-service", "open-ils.search");
System.out.println("2");
JSONObject data = new JSONObject();
JSONObject _p = new JSONObject();
JSONObject _p1 = new JSONObject();
JSONObject osrfmsg = new JSONObject();
HttpResponse response = null;
try {
_p.put("params",bookid);//"30007004981493"
_p.put("method","open-ils.search.biblio.find_by_barcode");
JSONObject payload = new JSONObject();
payload.put("_c", "osrfMethod");
payload.put("_p", _p);
_p1.put("threadTrace",0);
_p1.put("payload", payload);
_p1.put("locale","en-US" );
_p1.put("type", "REQUEST");
osrfmsg.put("_c","osrfMessage");
osrfmsg.put("_p",_p1);
data.put("osrf-msg",osrfmsg);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray osrfmsg2=new JSONArray();
osrfmsg2.put(osrfmsg);
httpost.getParams().setParameter("osrf-msg",osrfmsg2);
response = client.execute(httpost);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;)
{ builder.append(line).append("\n"); }
JSONTokener tokener = new JSONTokener(builder.toString());
JSONArray finalResult = new JSONArray(tokener);
but i'm not able to get the json array...
is there any other method?
Well you are constructing a JSONObject as the parameter,
try using
JSONArray as your payload object.
JSONArray payload = new JSONArray();
And work with a collection.
Hope that helps.
Also your context type that you send is not JSON, it is form encoded