将json对象转换为字符串并显示

yvgpqqbh  于 2023-01-10  发布在  其他
关注(0)|答案(4)|浏览(195)

基本上这里我使用url连接到php,一切都是在登录和注册阶段找到的工作,现在我想获取我在php文件中创建的json对象,然后在字符串视图中显示它,所以有人对此有想法吗?

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

}
下面是我的php文件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;

?>
dtcbnfnu

dtcbnfnu1#

您可以使用Java库GSON https://github.com/google/gson
要将json格式转换为java String.class,请编写:

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

z31licg02#

在回调进入onPostExecute之后,String参数可能是键-值对。因此要将String转换为JsonObject,请使用-

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

lmvvr0a83#

1.您可以使用
数据字段. setText(结果);
在onPostExecute()上
1.为了方便地从远程访问数据,可以使用POJO类的概念。
首先创建一个POJO类,如下所示

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

然后通过以下方式检索数据

BaseClass jsonObject = new BaseClass();
jsonObject = gson.fromJson(finalJson, BaseClass.class);
xqnpmsa8

xqnpmsa84#

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

相关问题