将 JSON 解析为 Parcelable 对象以将 Parcelable 对象发送到 Android 中的另一个 Activity

Parsing JSON to Parcelable objects to send Parcelable object to another Activity in Android

我想传递来自 POST 请求的 JSON 数据响应 API。我创建了实现 Parcelable class 的 Sharing class。我想利用 parcelable class 来保存几个对象(客户端信息)JSON 主要 activity 响应并将它们发送到第二个 activity 只显示客户端 information.Here 是我各自的代码, 这是 api 响应..{ "success": "true", "message": "Logged in successfuly", "user": { "id": 13, "userNo": "", "name": "Adam", "username": "Adam@gmail.com", "actualPassword": "12345", "email": "apollo@client.com", "secondaryEmail": null, "primaryPhone": 9876544345, "secondaryPhone": null, "clientId": { "clientId": 1, "name": "Charlie", "address": "India", "createdBy": null, "createdAt": "2018-10-25T11:25:19.000Z", "updatedAt": "2019-01-21T10:10:39.000Z", "is_active": 1, "clientCode": "APL", "startTime": "08:00:00.000000", "endTime": "07:59:59.000000", }, "gender": null, "dob": null, "emergencyMobile": null, "officeNo": null, "loggedInStatus": 0, } }

这是我的主要内容Activity..

public class MainActivity extends AppCompatActivity {


public  static String myUrl="IP Address URL Link";
TextView tvIsConnected;
EditText etEmail;
EditText etPassword;
TextView tvResult;
Button btn_Send;
String name="";

TextView client_ID;
TextView client_Name;
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    etEmail = findViewById(R.id.etEmail);
    etPassword = findViewById(R.id.etPassword);
    tvResult = (TextView) findViewById(R.id.tvResult);

    btn_Send =(Button)findViewById(R.id.btnSend);


    final HTTPAsyncTask process = new HTTPAsyncTask();
    btn_Send.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            process.execute();
        }
    });


}


@SuppressLint("ParcelCreator")
public  class HTTPAsyncTask extends AsyncTask<String, Void, String> implements Parcelable {
    JSONObject jsonObject = new JSONObject();
    Intent i = new Intent(MainActivity.this, DashboardActivity.class);

    @Override
    protected String doInBackground(String... urls) {

        StringBuffer output = new StringBuffer();
        try {
            try {

                URL url = new URL(myUrl);

                jsonObject.put("userName", etEmail.getText().toString());
                jsonObject.put("password", etPassword.getText().toString());



                HttpURLConnection conn = (HttpURLConnection) url.openConnection();

                conn.setReadTimeout(15000 );
                conn.setConnectTimeout(15000 );
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");



                OutputStream os = conn.getOutputStream();

                os.write(jsonObject.toString().getBytes());
                os.flush();
                BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
                String temp;
                while ((temp = br.readLine()) != null) {
                    output.append(temp);
                }
                conn.disconnect();

            } catch (JSONException e) {
                e.printStackTrace();
                return "Error";
            }
        }
        catch (IOException e) {
            return "Error while retrieving screen";
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        return output.toString();
}



    @Override
    public void onPostExecute(String result ) {



        i.putExtra("key",result);

        startActivity(i);



    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {

    }
}


}

以下是我的分享class实现了ParcelableClass..

public class SharingClass implements Parcelable {

private int ClientId ;
private String ClientName;
private String ClientAddress;

public SharingClass(){
    super();
}

public SharingClass(Parcel parcel){
    this.ClientId = parcel.readInt();
    this.ClientName = parcel.readString();
    this.ClientAddress = parcel.readString();
}

public SharingClass(Parcelable sharedObject) {
}

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeInt(ClientId);
    dest.writeString(ClientName);
    dest.writeString(ClientAddress);
}

public static final Creator<SharingClass> CREATOR = new Creator<SharingClass>() {
    @Override
    public SharingClass createFromParcel(Parcel parcel) {
        return new SharingClass(parcel);
    }

    @Override
    public SharingClass[] newArray(int i) {
        return new SharingClass[i];
    }
};

public void setClientId(int ClientId) {
    this.ClientId = ClientId;
}

public void setClientName(String ClientName) {
    this.ClientName = ClientName;
}

public void setClientAddress(String ClientAddress) {
    this.ClientAddress = ClientAddress;
}

public int getClientId() {
    return ClientId;
}

public String getClientName() {
    return ClientName;
}

public String getClientAddress() {
    return ClientAddress;
}


}

请给我一个访问 JSON 数据的解决方案,以在第二个 activity 中显示客户端信息,并显示解析,因为我是 Android[=16= 的新手]

既然你的对象实现了 Parcelable,那么只需使用 putExtra() 将它们放入你的 Intents 中即可:

Intent i = new Intent();
i.putExtra("name_of_extra", myParcelableObject);

然后你可以用getParcelableExtra():

把它们拉出来
Intent i = getIntent();
SharingClass sharingClass = (SharingClass) i.getParcelableExtra("name_of_extra");

如果您必须访问 POJO 中的数据,您可以使用 getter 方法获取,例如,在您的情况下。如果您必须访问 ClientId,那么您可以通过以下方式完成。

int clientId = sharingClass.getClientId();

希望这对您有所帮助。