我无法使用post volley android从嵌套的json对象中提取数据

时间:2022-10-08 09:26:11
{
"success": true,
"message": {
"user": {
  "firstName": "aaa",
  "lastName": "aaa",
  "email": "xxx@gmail.com",
  "role": 1,
  "profileUrl": ""
},
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjp7ImZpcnN0TmFtZSI6ImFhYSIsImxhc3ROYW1lIjoiYWFhIiwiZW1haWwiOiJ4eHhAZ21haWwuY29tIiwicm9sZSI6MSwicHJvZmlsZVVybCI6IiJ9LCJpYXQiOjE0ODY1MjMyOTAsImV4cCI6MTQ4NjUzNDczMH0.kFHji61mqqupMSNBL_ZLnaLbK1xmFxbD6MbWa_SPlyo",
"enum": {
  "_id": "5889d3f10893a7a42243998e",
  "updatedAt": "2017-01-26T10:48:17.233Z",
  "createdAt": "2017-01-26T10:48:17.233Z",
  "__v": 0,
  "mailCategories": [
    {
      "color": [
        "Work",
        "Document",
        "Social",
        "Advertising",
        "Client"
      ],
      "value": [
        "#1ab394",
        "#EF5352",
        "#1c84c6",
        "#23c6c8",
        "#F8AC59"
      ]
    }
  ],
  "folders": [
    "Send",
    "Draft"
  ],
  "uploadsImageTypes": [
    "jpg",
    "jpeg",
    "png",
    "gif"
  ],
  "uploadsFileTypes": [
    "jpg",
    "jpeg",
    "docx",
    "pdf",
    "txt",
    "ppt",
    "png",
    "gif"
  ],
  "workOrderStatus": {
    "color": [
      "#A09580",
      "#f8ac59",
      "#41b0f6",
      "#0d71b0",
      "#1ab394",
      "#067e47",
      "#2819bc",
      "#0d08f3",
      "#ef0c34",
      "#ef9aa9",
      "#f2830b"
    ],
    "value": [
      "Draft",
      "Requested",
      "Requested Awaiting Approval",
      "Assigned",
      "Work In Progress",
      "Ready",
      "Done",
      "Closed,Completed",
      "Closed,Incompleted",
      "On Hold",
      "Open"
    ]
  },
  "priorities": {
    "color": [
      "#0B7409",
      "#CE9B9B",
      "#7CC396",
      "#CEBE99"
    ],
    "value": [
      "Hard Down",
      "High",
      "Medium",
      "Low"
    ]
  },
  "categories": [
    "Equipment",
    "Cranes",
    "Delivery Vehicles",
    "Rotating Spares"
  ],
  "projects": [
    "Vehicle New",
    "System #7865",
    "Book Shop",
    "Site"
  ],
  "maintenanceTypes": {
    "color": "#FFFFFF",
    "bg_color": [
      "#1c84c6",
      "#262626",
      "#A09580",
      "#ed5565"
    ],
    "value": [
      "Electrical",
      "Damage",
      "Safty",
      "Broken"
    ]
  },
  "assets": [
    "Conveyor Belt 1",
    "Cranes",
    "Delivery Vehicles",
    "Rotating Spares"
  ],
  "assignToUser": [
    1,
    2,
    4,
    5,
    6
  ],
  "roles": [
    "Admin",
    "Manager",
    "Technician",
    "Customer",
    "Supplier",
    "Engineer",
    "Guest"
  ]
}
}
}

This is my LoginActivity.java

这是我的LoginActivity.java

public class LoginActivity extends AppCompatActivity {
EditText un, pw;
ImageButton sbtn;

SystemPreference systemPreference;

String URL_POST = "http://10.183.183.45:6663/api/v1/" + "auth/authenticate";

private GoogleApiClient client;

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

    un = (EditText) findViewById(R.id.login_username);
    pw = (EditText) findViewById(R.id.login_password);
    sbtn = (ImageButton) findViewById(R.id.signinbtn);

    sbtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            VolleyPost();
        }
    });
    client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}

private void VolleyPost() {

    systemPreference = SystemPreference.getInstance(this.getApplicationContext());

    StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_POST, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.d("response", String.valueOf(response));

            JSONObject jsonObject = null;
            try {
                JSONObject msgjson = new JSONObject(response);
                String success = msgjson.getString("success");
                String message = msgjson.getString("message");

                JSONObject tokenObj = new JSONObject("token");
                String token = tokenObj.getString("token");

                if(msgjson.isNull(token)) {
                    String msg = msgjson.get("user").toString();
                    Log.d("msg",  msg);
                    Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
                }else {
                    String msg = msgjson.get("message").toString();

                    Log.d("msg",  msg);
                    Toast.makeText(LoginActivity.this, "Authorized User", Toast.LENGTH_SHORT).show();
                    Intent i = new Intent(LoginActivity.this, MenuActivity.class);
                    startActivity(i);

                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d("aaa", "aaa");
            Toast.makeText(LoginActivity.this, "Wrong password or username", Toast.LENGTH_SHORT).show();
        }
    }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<String, String>();
            String email = un.getText().toString();
            String password = pw.getText().toString();
            params.put("email", email);
            params.put("password", password);

            return params;
        }
    };

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}

}

How can I extract token to a string?

如何将令牌提取到字符串?

4 个解决方案

#1


0  

JSONObject msgjson = new JSONObject(response);
                String success = msgjson.getString("success");
                String message = msgjson.getString("message");

                JSONObject tokenObj = new JSONObject(message); //change to this
                String token = tokenObj.getString("token");

You are creating json object with nothing!!!

你正在创建没有任何东西的json对象!

#2


0  

you can use getAsJsonPrimitive method

你可以使用getAsJsonPrimitive方法

JSONObject msgjson = new JSONObject(response); msgjson.getAsJsonPrimitive("token").getAsString();

JSONObject msgjson = new JSONObject(response); msgjson.getAsJsonPrimitive( “令牌”)符getAsString();

#3


0  

Try this,

尝试这个,

            JSONObject jObj=new JSONObject(response);
            String success=jObj.getString("success");
            JSONObject objMsg=jObj.getJSONObject("message");

            /* get token */
            String token=objMsg.getString("token");

             /* get user data */
            JSONObject objUser=objMsg.getJSONObject("user");
            String firstName=objUser.getString("firstName");
            String lastName=objUser.getString("lastName");
            String email=objUser.getString("email");

#4


0  

token is string which is inside the message object So, you have to do the following

token是消息对象内部的字符串因此,您必须执行以下操作

JSONObject responseJSON = new JSONObject(response);
JSONObject msgObject=responseJSON.getJSONObject("message");
String token=msgObject.getString("token");

you are seeing that,

你看到了,

 {} this denotes Object
 [] this denotes array
 "" this denotes string

#1


0  

JSONObject msgjson = new JSONObject(response);
                String success = msgjson.getString("success");
                String message = msgjson.getString("message");

                JSONObject tokenObj = new JSONObject(message); //change to this
                String token = tokenObj.getString("token");

You are creating json object with nothing!!!

你正在创建没有任何东西的json对象!

#2


0  

you can use getAsJsonPrimitive method

你可以使用getAsJsonPrimitive方法

JSONObject msgjson = new JSONObject(response); msgjson.getAsJsonPrimitive("token").getAsString();

JSONObject msgjson = new JSONObject(response); msgjson.getAsJsonPrimitive( “令牌”)符getAsString();

#3


0  

Try this,

尝试这个,

            JSONObject jObj=new JSONObject(response);
            String success=jObj.getString("success");
            JSONObject objMsg=jObj.getJSONObject("message");

            /* get token */
            String token=objMsg.getString("token");

             /* get user data */
            JSONObject objUser=objMsg.getJSONObject("user");
            String firstName=objUser.getString("firstName");
            String lastName=objUser.getString("lastName");
            String email=objUser.getString("email");

#4


0  

token is string which is inside the message object So, you have to do the following

token是消息对象内部的字符串因此,您必须执行以下操作

JSONObject responseJSON = new JSONObject(response);
JSONObject msgObject=responseJSON.getJSONObject("message");
String token=msgObject.getString("token");

you are seeing that,

你看到了,

 {} this denotes Object
 [] this denotes array
 "" this denotes string