简体   繁体   中英

convert json object to string and display

Basically here im using url connection to connect to php, everything is work find in log in and register phase, now i want to fetch the json object that i create in php file and then display it in a string view, so anyone got idea regarding this?

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display);

    dataField = (TextView) findViewById(R.id.data);
    btnDis = (Button) findViewById(R.id.btnClick);




    btnDis.setOnClickListener (new View.OnClickListener(){
        @Override
        public void onClick(View v){

            strUrl ="http://10.0.2.2/android/display.php";

            new jsonParse().execute();
        }
    });
}




public class jsonParse extends AsyncTask<String, String, String>{
    @Override
    protected void onPreExecute() {

        super.onPreExecute();

    }

    @Override
    protected void onPostExecute(String s) {

        Toast.makeText(EditActivity.this,""+result,Toast.LENGTH_LONG ).show();
    }

    @Override
    protected String doInBackground(String... params) {
        try{
            URL url = new URL (strUrl);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("POST");
            con.connect();

            //get response from server
            BufferedReader bf = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String value = bf.readLine();
            System.out.println("result is"+value);
            result = value;

            String finalJson = bf.toString();
            JSONObject parentObject = new JSONObject(finalJson);
            JSONArray parentArray = parentObject.getJSONArray("data");

            JSONObject finalObject= parentArray.getJSONObject(0);
            String username = finalObject.getString("NAME");
            String age = finalObject.getString("AGE");
            String result = username +" - "+age;
            return result;
        }


        catch(Exception e){
            System.out.println(e);
        }

        return null;
    }
}

}

Here is my php file called display.php

<?php
require "conn.php";
require_once "global.php";



//get record from databases
$query = "SELECT * FROM user";
if($result = mysqli_query($conn, $query)){
  // printf("%d", mysqli_num_rows($result));

if(mysqli_num_rows($result) > 0){
  $status = 'true';
  $message = 'data retrieved successfully';
      while($row = mysqli_fetch_assoc($result)){
        $name = $row['name'];
        $age = $row['age'];
        $username = $row['username'];


        // echo $name."\n\n";
        // echo $age."\n\n";
        // echo $username."\n\n";

        $data .= '{"NAME" : "'.$name.'", "AGE" : "'.$age.'", "USERNAME" : "'.$username.'"},';
      }

}else{
  $status = 'false';
  $message = 'data retrieved failed';
  $data = '';
}

mysqli_free_result($result);
mysqli_close($conn);
}else{
  $message = mysqli_error($conn);
}
$output = '{"status": "'.$status.'","message":"'.$message.'", "data": ['.rtrim($data, ',').']}';
echo $output;

?>

You can use java library GSON https://github.com/google/gson .

To convert json format to java String.class write:

String str = gson.fromJson("\"abc\"", String.class);

After the callback comes in onPostExecute, the String arguments may be in key-value pair. So to convert String to JsonObject use -

@Override
protected void onPostExecute(String s) {
 try {
        JSONObject jsonObject = new JSONObject(s);
    } catch (JSONException e) {
        e.printStackTrace();
     }
}
  1. You can use

    dataField.setText(result);

on onPostExecute()

  1. For easily accessing your data from remote you can use the concept of POJO class.

First create a POJO class like this

class BaseClass {
    Boolean status;
    String message;
    String data;
    RowClass row;

    public Boolean getStatus() {
        return status;
    }

    public String getMessage() {
        return message;
    }

    public String getData() {
        return data;
    }

    public RowClass getRow() {
        return row;
    }

    class RowClass {
        String name;
        String username;
        int age;
        String data;

        public String getName() {
            return name;
        }

        public String getUsername() {
            return username;
        }

        public int getAge() {
            return age;
        }

        public String getData() {
            return data;
        }
    }
}

and then retrieve data by

BaseClass jsonObject = new BaseClass();
jsonObject = gson.fromJson(finalJson, BaseClass.class);
private static String jsonToString(final Object obj) {
    String result;
    try {
        final ObjectMapper mapper = new ObjectMapper();
        final String jsonContent = mapper.writeValueAsString(obj);
        result = jsonContent;
    } catch (JsonProcessingException e) {
        result = "JSON Parsing error";
    }
    return result;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM