public class MainActivity extends AppCompatActivity {
String jsonData;
Response response;
JSONArray Jarray;
private String TAG;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new
StrictMode.setThreadPolicy(policy);
OkHttpClient client = new OkHttpClient();
String token="a";
RequestBody body = new FormBody.Builder()
.add("Token",token)
.build();
Request request = new Request.Builder()
.url("http://www.auffers.com/test/index.php")
.post(body)
.build();
Response response = null;
try {
response = client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
if (!response.isSuccessful()) try {
throw new IOException("Unexpected code " + response);
} catch (IOException e) {
e.printStackTrace();
}
Headers responseHeaders = response.headers();
for (int i = 0; i < responseHeaders.size(); i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
try {
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}}
给了我{ "name":"John", "age":31, "city":"New York" }
但我无法获得不同的元素,如姓名,年龄,城市,以便我可以将它们保存在我的数据库中。我已经研究了许多答案,但却无法做到这一点
有人可以帮我解决这个问题吗?
答案 0 :(得分:1)
尝试
try {
JSONObject json = new JSONObject(response.body().string());
String name = json.getString("name");
String city = json.getString("city");
int age = json.getInt("age");
} catch (JSONException e) {
e.printStackTrace();
}