使用REST TEMPLATE时从JSON获取ID

时间:2017-11-20 15:23:37

标签: android json resttemplate

我正在使用Resttemplate进行网络连接。它工作得很好,但我不知道如何从服务器响应中精确提取特定参数。

响应正文如下:

{
    "userdata": {
        "id": "9981",
        "userid": "5a01cda4a00a3",
        "login": "yikes@test.de",
        "name": "yikes",
        "vorname": "yikes",
        "passwort": "3136b44e1c508d36ae4abf6f1160f779",
        "email": "yikes@test.de",
        "reg_date": "2017-11-07 16:13:40",

依旧.....

编辑:

try {

                    RestTemplate template = new RestTemplate();
                    final String Login = "https://app.pengueen.de//api/v1/login/?";
                    final String username1 = "username";
                    final String password1 = "password";
                    final String apikey = "api_key";


                    Uri builtUri = Uri.parse(Login)
                            .buildUpon()
                            .appendQueryParameter(username1, username.getText().toString())
                            .appendQueryParameter(password1, password.getText().toString())
                            .appendQueryParameter(apikey, "awd-DFFDD-dsse$5")
                            .build();
                   String  url = (builtUri.toString());
                       //Umwandelnb damit url conevter nichts abfuckt
                        URI uri = new URI(url);

                        //Error Handeler
                        template.setErrorHandler(new DefaultResponseErrorHandler(){
                            protected boolean hasError(HttpStatus statusCode) {
                                return false;
                            }});

                        //Response von Post bekommen
                        response = template.postForEntity(uri, null, String.class);
                        HttpStatus status = response.getStatusCode();
                        String restCall = response.getBody();






                } catch (URISyntaxException e) {


                        e.printStackTrace();

                    }
                    if (response.getStatusCode().toString().equals("200")) {

/ /这里我想获得id,所以我可以将它传递给下一堂课!

                        Toast.makeText(getApplicationContext(), "Login erfolgreich", Toast.LENGTH_LONG).show();
                        Intent intent=new Intent(LoginScreen9.this,SideMenu1.class);
                        intent.putExtra("loginy","true");
                        intent.putExtra("id",response.getBody());
                        startActivity(intent);

                    }

提前谢谢!

1 个答案:

答案 0 :(得分:1)

好的,尝试使用JSONObject:

   String restCall = response.getBody();
   JSONObject jObject = new JSONObject(restCall); 
   JSONObject userObject = jObject.getJSONObject("userdata");
   String id = userObject.getString("id");