variables of an array with the same name

2

I have 2 arrays in Java with different Array names (sender and recipient), but the variables within the arrays are the same (account_number, product_id, external_id, simulation, recipient_sms_notification, sender_sms_notification), when declaring them I must call them variables within the arrays, how do I call it and be able to distinguish between them?

String message;
JSONObject json = new JSONObject();
json.put("account_number",account_number);
json.put("product_id", product_id);
json.put("external_id", external_id);
json.put("simulation", simulation);
json.put("recipient_sms_notification", recipient_sms_notification);
json.put("sender_sms_notification", sender_sms_notification);

JSONArray array = new JSONArray();
JSONObject item = new JSONObject();
item.put("last_name", last_name);
item.put("middle_name", middle_name);
item.put("first_name", first_name);
item.put("email", email);
item.put("mobile", mobile);

array.put(item);
json.put("sender", array);

JSONArray array2 = new JSONArray();
JSONObject item2 = new JSONObject();
item.put("last_name", last_name);
item.put("middle_name", middle_name);
item.put("first_name", first_name);
item.put("email", email);
item.put("mobile", mobile);
array.put(item);
json.put("recipient", array);

message = json.toString();
    
asked by mestanza 11.05.2016 в 17:52
source

1 answer

1

I commented that Java is an object-oriented programming language, therefore, the correct approach is to create a class Sender and a class Recipient with their respective attributes, even if they have common attributes, you should create a third class "father" of which inherit Sender and Recipient . Then you simply create Arrays of Sender and Recipient and call their attributes accordingly. But your problem can be solved as follows:

JSONArray senderArray = new JSONArray();
JSONObject senderDetail = new JSONObject();
senderDetail.put("sender.last_name", last_name);
senderDetail.put("sender.middle_name", middle_name);
senderDetail.put("sender.first_name", first_name);
senderDetail.put("sender.email", email);
senderDetail.put("sender.mobile", mobile);
senderArray.put(senderDetail);
json.put("sender", senderArray);

JSONArray recipientArray = new JSONArray();
JSONObject recipientDetail = new JSONObject();
recipientDetail.put("recipient.last_name", last_name);
recipientDetail.put("recipient.middle_name", middle_name);
recipientDetail.put("recipient.first_name", first_name);
recipientDetail.put("recipient.email", email);
recipientDetail.put("recipient.mobile", mobile);
recipientArray.put(recipient.recipientDetail);
json.put("recipient", recipientArray);

message = json.toString();
    
answered by 16.05.2016 в 16:17