如何使用正则表达式通过服务器拆分响应

How to split response through server using regex

我想拆分通过服务器收到的响应,以便我可以取值,并在文本上设置..但我不能取值...

响应:{"status":"no","requestCount":"0","estelamCount":"0"}

                    String[] split_model = response.split(",");
                  //  Log.i("split_model",split_model);
                    Log.i("phoneName", split_model[0]);

日志 == > I/phoneName: {"status":"no"

        String status ="";

        JSONObject jsonObject = new JSONObject(response); //convert to json

        if (jsonObject.has("status")){ //check if has the key
            status = jsonObject.getString("status"); // get the value
        }else{

        }

        Log.d("TAG", status); // do sth with the value

        //Log => status

我想你问的是如何解析你的回复,你就是这样做的

JSONObject myJson = new JSONObject(response);

String status = myJson.optString("status");
String count = myJson.optString("requestCount");
String estelamCount = myJson.optString("estelamCount");

您从服务器接收 json 数据,因此您可以将其解析为 json,如先前的答案所指出的。更好的是,您可以使用 Gson 库来解析数据,如下所示, 1- 创建一个代表您的响应的 class,您可以使用 http://www.jsonschema2pojo.org/ 之类的工具来实现此目的,只需粘贴您的 json 字符串,然后从右侧的选项中选择 Java 作为目标语言,Json 作为源类型,Gson 作为注解风格,然后输入任何你想使用的 class 名称,结果应该是这样的 包裹 com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Response {

@SerializedName("status")
@Expose
public String status;
@SerializedName("requestCount")
@Expose
public String requestCount;
@SerializedName("estelamCount")
@Expose
public String estelamCount;
}

那么当你想对结果进行处理时,可以按如下方式进行

Gson gson = new Gson();
//now you can parse the response string you received, here is responseString
Response response = gson.fromJson(responseString, Response.class);
//now you can access any field using the response object 
Log.d("Reponse" , "status =  " + response.status  + ", requestCount = " + response.requestCount + ", estelamCount = " + response.estelamCount ;