i have created a rest wcf web service and hosted in local iis, the json string is converted with JsonConvert.SerializeObject(object) of Newtonsoft package.
the output of the web service is
"[{\"companyId\":2,\"companyName\":\"A\"},
{\"companyId\":8,\"companyName\":\"B\"}]"
this web service is consume by android apps,
i tried with JSONArray and JSONObject but it keep on throwing exception
org.json.JSONException: Expected literal value at character 2 of
[{\"companyId\":2,\"companyName\":\"A\"},{\"companyId\":8,\"companyName\":\"B\"}]
org.json.JSONException: Expected literal value at character 2 of
"[{\"companyId\":2,\"companyName\":\"A\"},
{\"companyId\":8,\"companyName\":\"B\"}]"
org.json.JSONException: Value [{"companyId":2,"companyName":"A"},
{"companyId":8,"companyName":"B"}] of type java.lang.String cannot be
converted to JSONArray
this is the code in android class
public JSONArray RequestWebService(URL urlToRequest) {
urlConnection = (HttpURLConnection) urlToRequest.openConnection();
urlConnection.setConnectTimeout(CONNECTION_TIMEOUT);
urlConnection.setReadTimeout(RETRIEVE_TIMEOUT);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
int statusCode = urlConnection.getResponseCode();
if (statusCode == HttpURLConnection.HTTP_OK) {
InputStream in = new BufferedInputStream(
urlConnection.getInputStream());
String result = getResponseText(in);
//result = result.substring(1, result.length() - 1);
//result = result.replace("/\\/g", "");
JSONArray j = new JSONArray(result);
return j
}
return null;
}
private String getResponseText(InputStream inStream) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader rd = null;
try{
rd = new BufferedReader(new InputStreamReader(inStream));
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
}finally {
if (rd != null) {
rd.close();
}
}
return sb.toString();
}
String response = "Your Response";
try{
JsonArray jAry = new JsonArray(response);
JsonObjct jObj;
for(int i=0;i<jAry.length;i++){
jObj = JAry.getJsonObject(i);
// You can get your string from object jobj and also use it by store it value in arraylist.
}
} catch(Exception e){
}
Related
I have following response from post request using HttpURLConnection:
Post Request Response:
{
"LatestData": [{
"ExtraData": null,
"ID": 0,
"season": false,
"latest": 0,
"url": "http://www.awebsite.com/images/12.jpg"
}]
}
How to get value of URL? I tried following but Android Studio keeps giving me error:
String newURL = sb.getJSONObject("LatestData").getString("url");
String newURL = sb.getJSONArray("LatestData").getJSONObject(0).getString("url");
Android Studio Error:
error: cannot find symbol method getJSONObject(String)
error: cannot find symbol method getJSONArray(String)
could you guys help me obtain the value of url and let me know what libraries i need to import to android studio so getsonObject works ?Thanks
android code:
if (myURLConnection.getResponseCode() == 200) {
br = new BufferedReader(new InputStreamReader(myURLConnection.getInputStream(), "utf-8"));
while (true) {
line = br.readLine();
if (line != null) {
sb.append(line + "\n");
//String newURL = sb.getJSONObject("LatestData").getString("url");
String newURL =sb.getJSONArray("LatestData").getJSONObject(0).getString("url");
mWebView.loadUrl("javascript:MyFunction('" +newURL + "');");
} else {
br.close();
return sb.toString();
}
}
}
You need to convert sb to a JSONObject to access properties:
JSONOjbect jsonResponse = new JSONObject(new String(sb));
and then:
try {
JSONArray jsonArray = jsonResponse.getJSONArray("LatestData");
if (jsonArray != null && jsonArray.length() > 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject dataOjbect = jsonArray.getJSONObject(i);
String url = dataOjbect.getString("url");
}
}
} catch (Exception e) {
e.printStackTrace();
}
try {
JSONObject jsonObject = new JSONObject(sb);
String url = jsonObject.optJSONArray("LatestData").getJSONObject(0).optString("url");
} catch (JSONException e) {
e.printStackTrace();
}
Try it using loadJSONArray
String url = loadJSONArray(sb)..getJSONObject(0).getString("url");
Your approach should be like this.
try {
List<String> urlist = new ArrayList<>();
JSONObject jsonObject = new JSONObject(sb.toString());
JSONArray jsonArray = jsonObject.getJSONArray("LatestData");
for (int count = 0; count<jsonArray.length(); count++){
JSONObject jsonInner = jsonArray.getJSONObject(count);
String url = jsonInner.getString("url");
//store your url in some list
urlist.add(url);
}
} catch (JSONException e) {
e.printStackTrace();
}
Can you try this :
StringBuilder sb = new StringBuilder();
line = br.readLine();
while(line != null){
sb.append(line);
}
// if it's fail here then this means there is an issue in parsing JSONObject
JSONObject jsonObj = new JSONObject(sb.toString());
JSONArray latestData = jsonObj.getJSONArray("LatestData");
JSONObject jsonObject = latestData.getJSONObject(0);
String url = jsonObject.getString("url");
Also I'm highly recommending to use Retrofit with GSON .. you can follow this article : http://www.vogella.com/tutorials/Retrofit/article.html
use jsonschema2pojo to generate pojo classes for a JSON data
I have a program that reads in a CSV file and returns a JSON String.
However using JsonArray and JsonObject only yield the last row of results from the file. How do I concat numerous rows of data into a JSON object?
Output
[{"name":"Other_Renwables","load":"14.3"},{"name":"Other_Renwables","load":"14.3"},{"name":"Other_Renwables","load":"14.3"},{"name":"Other_Renwables","load":"14.3"},{"name":"Other_Renwables","load":"14.3"},{"name":"Other_Renwables","load":"14.3"}]
Code
JSONObject jObject = new JSONObject();
JSONArray jArray = new JSONArray();
int count = 0;
try{
logger.info("\nSending 'GET' request to URL : " + url);
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpClient.execute(httpGet);
int responseCode = response.getStatusLine().getStatusCode();
logger.info("Response Code : " + responseCode);
if (responseCode != 404){
try(BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent()))) {
if(reader != null){
//StringBuilder builder = new StringBuilder();
String aux = "";
while ((aux = reader.readLine()) != null) {
String[] tab = aux.split(",");
if (count > 0){
try {
jObject.put("name", tab[0]);
jObject.put("load", tab[1]);
jArray.put(jObject);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
count++;
}
retVal = jArray.toString();
}
}
}
return retVal;
}finally{
httpClient.getConnectionManager().shutdown();
}
You are using same object and over-writing it in your loop.
This instantiation:
JSONObject jObject = new JSONObject();
must be in your loop.
try {
JSONObject jObject = new JSONObject();
jObject.put("name", tab[0]);
jObject.put("load", tab[1]);
jArray.put(jObject);
}
I have a webservice that returnds a json response , the json response contains both plain text and base64 encoded images , I am consuming that service using android app so I implemented progress bar to indicate the progress .
Implementing progress bar forces me to use BufferedInputStream to read the response and update the progress based on what the app is reading .
The problem is that everything is working fine and the progress is updating correctly, but after collecting the response and exiting the while loop , I try to convert the string into json format using JSONObject.
Here is the code snippet
BufferedInputStream bis = new BufferedInputStream(responseEntity.getContent());
StringBuilder sb = new StringBuilder();
String line = null;
int total = 0 ;
int count = 0 ;
byte[] buffer = new byte[4096];
StringBuffer sBuffer = new StringBuffer();
StringWriter sw = new StringWriter();
String content = new String();
while((count = bis.read(buffer)) > 0){
content += new String(buffer,Charset.defaultCharset());
total += count;
publishProgress(""+(int )total*100/this.contentSize);
Log.i("updating",""+(int )total*100/this.contentSize);
}
bis.close();
// String content = new String(sb);
// Log.i("ServerRawresponse",content);
try {
Log.i("REsponse_Content",content.replaceAll("\"", ""));
responseString = new JSONObject(new JSONTokener(content.replaceAll("\"", "\\\"")));
//System.out.println(content);
} catch (JSONException e) {
e.printStackTrace();
}
Any help please
Try this methods works perfectly with me
HttpResponse WSresponse = httpclient.execute(httppost);
String response = getResponseBody(WSresponse.getEntity());
JSONObject jobj = new JSONObject(response);
public String getResponseBody(final HttpEntity entity) throws IOException, ParseException {
System.out.println("GEN START : " + Calendar.getInstance().getTimeInMillis());
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
InputStream instream = entity.getContent();
if (instream == null) {
return "";
}
if (entity.getContentLength() > Integer.MAX_VALUE) {
throw new IllegalArgumentException(
"HTTP entity too large to be buffered in memory");
}
StringBuilder buffer = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream, HTTP.UTF_8));
String line = null;
try {
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
} finally {
instream.close();
reader.close();
}
return buffer.toString();
}
I'm trying to get a json string from a url and my method is returning a null string value when I use this line of code:
String jsonStr = getJsonStringFromURL(url);
Here is the method I'm using:
public static String getJsonStringFromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jsonObject = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch (Exception e) {
return null;
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
}
catch(Exception e) {
return null;
}
return result;
}
I have a url variable used where when I copy and paste the url into a browser it does return and display a json string. Any suggestions or help would be greatly appreciated.
The thing is you assigning value to the result when BufferReader is closed. Thats why you getting the null value.
Instead of assigning result = sb.toString(); outside of the BufferReader assign it before closing it.
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
System.out.println(result);// It will print you the value
is.close();
Hope it helps.
My JSON array is this:
{"Name_1":1,"Name_2":0,"Name_3":0}
and my code in java for getting the values and store them in a separate array is the following:
int[] operations= new int[3];
String result = "";
InputStream is = null;
StringBuilder sb=null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://testteamgr.netau.net/parsing/test.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
try{
JSONObject json_data = new JSONObject(result);
System.out.println("Length of json is"+jArray.length());
for(int i=0;i<jArray.length();i++){
if (i==0) operations[0]=json_data.getInt("Name_1");
else if (i==1) operations[1]=json_data.getInt("Name_2");
else if (i==2) operations[2]=json_data.getInt("Name_3"); }
and I am getting those errors:
value br of type java.lang.string cannot be converted to jsonobject
If I print out the result I do not see the JSONobject but the html code.
So what I want is to get these 3 values into a separate array.
You have an object, not an array. To process the result you can use following code:
String json = "{\"Name_1\":1,\"Name_2\":0,\"Name_3\":0}";
JSONObject object = new JSONObject(json);
String[] propertyNames = JSONObject.getNames(object);
String[] values = new String[propertyNames.length];
for (int i = 0; i < propertyNames.length; i++) {
values[i] = String.valueOf(object.get(propertyNames[i]));
}