Concatinating JSON elements using java-json - java

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);
}

Related

How to get a specific json key value from post request response in Android?

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

cannot convert Json string to JSONObject or JSONArray

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){
}

Transfering Base64 String over Http REST service with JSON response

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();
}

Send POST to a web service and verify some data and send back as JSON

!
I am working on a quiz-app that uses a PHP web service to author/host/maintain data for the Android quizes.
Heres is the PHP function in question.
I am looking for a post in my PHP code.
if (isset($_POST['verifyCourse'])){
verifyCourse($_POST['courseCode']);}
Any then this points to the function...
function verifyCourse($courseCode){
$result = mysql_query("SELECT * FROM Course WHERE CourseCode = \"$courseCode\";");
$rows = array();
while ($r = mysql_fetch_assoc($result)) {
$rows = $r;
}
if($rows == null){
return 0;
} else {
return json_encode(array('Course' => $rows));
}
}
And then on my Android code I am doing this to send a POST to the server called "verifyCourse" but I am getting nothing in return.
Android: Function to send HTTP POSTS
public ArrayList<HashMap<String, String>> httpPost(List<NameValuePair> valuepair, String code)
{
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://mydomain.edu/quiz-app/webservice.php");
StringBuilder builder = new StringBuilder();
try {
httppost.setEntity(new UrlEncodedFormEntity(valuepair));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
/* Checking response */
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream in = entity.getContent();
Log.d("myapp", "response " + response.getEntity());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
}else{
Log.e("POST-return", "Failed to download file");
}
} catch (Exception e) {
}
ArrayList<HashMap<String, String>> results = new ArrayList<HashMap<String, String>>();
HashMap<String, String> storage = new HashMap<String, String>();
String value;
try{
JSONArray jArray = new JSONArray(builder.toString());
for(int i=0; i<jArray.length(); i++){
JSONObject jsonObject = jArray.getJSONObject(i);
value=jsonObject.getString(code);
storage = new HashMap<String, String>();
storage.put(code, value);
results.add(storage);
}
} catch (Exception e) {
}
return results;
}
I then am using it like this to execute the functionality.
/// pass a code from other section of app
public void getCourseCodesandVerify(String code) {
List<NameValuePair> course_info = new ArrayList<NameValuePair>(2);
course_info.add(new BasicNameValuePair("verifyCourse",null));
course_info.add(new BasicNameValuePair("courseCode",code));
httpPost(course_info,null);
}
Any idea why my code just returns nothing...?
Heres what I get back for JSON, how do I process this?
mysql_fetch_assoc returns an array. So in your code you get something like:
echo json_encode(array('Course' => array()));
the result is a string: {"Course":[]}. In JSON this is an object. so you need to fetch it with:
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jArray = jsonObject.getJSONArray("Course");
See also: Reading a Json Array in android
update
in your php:
function verifyCourse($courseCode){
$result = mysql_query("SELECT * FROM Course WHERE CourseCode = \"$courseCode\" LIMIT 1");
$rows = array();
while ($r = mysql_fetch_assoc($result))
{
$rows[]= $r;
}
header('Content-type: application/json');
return json_encode(array('Course' => $rows));
exit;
}
Which outputs a string like:
{"Course":[{"key1":"value1","key2":"value2"},{"2key1":"2value1","2key2":null}]}
in your java code:
JSONObject jsonObject = new JSONObject(builder.toString());
JSONArray jArray = jsonObject.getJSONArray("Course");
for(int i = 0; i < jArray.length(); i++){
JSONObject jObject = jArray.getJSONObject(i);
Iterator<String> keys = jObject.keys();
storage = new HashMap<String, String>();
while( keys.hasNext() ){
String key = (String)keys.next();
storage.put(key, jObject.get(key).toString());
}
results.add(storage);
}

json data fetched from php and store them in an array in java

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]));
}

Categories