How do I get only 1678 and 300322459062776319 from the below JSON output ?
{
"timestamp": 1648620186101,
"status": "OK",
"statusCode": 200,
"message": "GET response successful.",
"content": [
{
"TRN Amount": "891, 1678",
"TRN Number": "300322194233562569, 300322459062776319"
}
]
}
CodePudding user response:
First breakdown the JSON object and get the JSON Array.
From the Array, get each JSON String from the JSON object inside of it.
Then split the string and get the last element and parse it to Long.
Code:
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.ParseException;
import org.json.simple.parser.JSONParser;
public class LastJSON {
public static void main(String[] args) throws ParseException {
JSONParser parser = new JSONParser();
String JSON = "{ \"timestamp\": 1648620186101, \"status\": \"OK\", \"statusCode\": 200, \"message\": \"GET response successful.\", \"content\": [ { \"TRN Amount\": \"891, 1678\", \"TRN Number\": \"300322194233562569, 300322459062776319\" } ] }";
JSONObject jsonObject = (JSONObject) parser.parse(JSON);
JSONArray content = (JSONArray) jsonObject.get("content");
String[] TRN_AMOUNT = ((JSONObject) content.get(0)).get("TRN Amount").toString().split(",");
String[] TRN_NUMBER = ((JSONObject) content.get(0)).get("TRN Number").toString().split(",");
long lastAmount = Long.parseLong(TRN_AMOUNT[TRN_AMOUNT.length-1].trim());
long lastNumber = Long.parseLong(TRN_NUMBER[TRN_NUMBER.length-1].trim());
System.out.println("Last Amount: " lastAmount);
System.out.println("Last Number: " lastNumber);
}
}
Output:
Last Amount: 1678
Last Number: 300322459062776319