I have a json file that has the following contents:
{
"Security": {
"UsernameToken": {
"Username": "username",
"Password": "password"
},
"UPSServiceAccessToken": {
"AccessLicenseNumber": "AccessKey01"
}
},
"XAVRequest": {
"Request": {
"RequestOption": "1",
"TransactionReference": {
"CustomerContext": "Verify that an XAV request with an Address Line 1 element returns a successful response.",
"TransactionIdentifier": ""
}
},
"RegionalRequestIndicator": "",
"MaximumListSize": "10",
"AddressKeyFormat": {
"ConsigneeName": "RITZ CAMERA CENTERS-1749",
"BuildingName": "Innoplex",
"AddressLine": [
"26601 ALISO CREEK ROAD",
"STE D",
"ALISO VIEJO TOWN CENTER"
],
"Region": "ROSWELL,GA,30075-1521",
"PoliticalDivision2": "ALISO VIEJO",
"PoliticalDivision1": "CA",
"PostcodePrimaryLow": "92656",
"PostcodeExtendedLow": "1521",
"Urbanization": "porto arundal",
"CountryCode": "US"
}
}
}
I am trying to read values out of the Security container and the Request container into seperate variables and then re-write the file without the Security and Request containers. The final file should look like this:
{
"XAVRequest": {
"RegionalRequestIndicator": "",
"MaximumListSize": "10",
"AddressKeyFormat": {
"ConsigneeName": "RITZ CAMERA CENTERS-1749",
"BuildingName": "Innoplex",
"AddressLine": [
"26601 ALISO CREEK ROAD",
"STE D",
"ALISO VIEJO TOWN CENTER"
],
"Region": "ROSWELL,GA,30075-1521",
"PoliticalDivision2": "ALISO VIEJO",
"PoliticalDivision1": "CA",
"PostcodePrimaryLow": "92656",
"PostcodeExtendedLow": "1521",
"Urbanization": "porto arundal",
"CountryCode": "US"
}
}
The problem that I am running into is that the base name (in this case XAVRequest) will not always be the same. So I need the file to keep the base name, read the elements that I mention before, store them in variables, and then write the remaining objects. I am running into issues. Here is what I have so far:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package tester;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class Tester {
static String username, password, accesskey, reqOption = "", reqStr;
@SuppressWarnings("unchecked")
public static void main(String[] args) {
JSONParser jsonParser = new JSONParser();
Object obj;
try (FileReader reader = new FileReader("14771_req.rest.json")) {
//Read JSON file
obj = jsonParser.parse(reader);
JSONObject jsonObject = (JSONObject) obj;
//Handle the security object
HandleSecurityObject(jsonObject);
//Handle the object Body
JSONObject reqBody = HandleRequestObject(jsonObject);
//Remove the Request Container and write the file new file
GetRestObject(reqBody;
} catch (FileNotFoundException e) {
System.out.println("Could not find the reference file");
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}
private static void printJsonObject(JSONObject sec) {
for (Object key : sec.keySet()) {
//based on you key types
String keyStr = (String) key;
Object keyvalue = sec.get(keyStr);
switch (keyStr) {
case "AccessLicenseNumber":
accesskey = (String) keyvalue;
// System.out.println(accesskey);
break;
case "Username":
username = (String) keyvalue;
// System.out.println(username);
break;
case "Password":
password = (String) keyvalue;
// System.out.println(password);
break;
case "RequestOption":
reqOption = (String) keyvalue;
// System.out.println(reqOption);
break;
}
if (keyvalue instanceof JSONObject) {
printJsonObject((JSONObject) keyvalue);
}
}
}
private static void HandleSecurityObject(JSONObject jsonObject) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
//1. Get security header information and store in variable try 'Security' first
JSONObject sec = (JSONObject) jsonObject.get("Security");
if (sec.isEmpty()) {
sec = (JSONObject) jsonObject.get("UPSSecurity"); //try 'UPSSecurity'
}
System.out.println("Security object: " + sec);
printJsonObject(sec);
// return sec.toString();
}
private static JSONObject HandleRequestObject(JSONObject jsonObject) {
JSONObject reqBody = null;
for (Object key : jsonObject.keySet()) {
//Read key, act if not Security Container
String keyStr = (String) key;
if (!(keyStr.equalsIgnoreCase("Security")) && !(keyStr.equalsIgnoreCase("UPPFSecurity"))) {
System.out.println("Key After comparison " +key);
reqStr = keyStr;
System.out.println("KeyString after comparison " + keyStr);
JSONObject body = (JSONObject) jsonObject.get(keyStr);
System.out.println("Body" + body);
reqBody = body;
System.out.println("reqBody" + reqBody);
}
}
return reqBody;
}
private static void writeNewRestFile(String keyStr, JSONObject body) {
BufferedWriter bw = null;
try {
File file = new File("14771_new_req.rest.json");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file);
bw = new BufferedWriter(fw);
if (!(keyStr.equalsIgnoreCase("Security")) || !(keyStr.equalsIgnoreCase("UPPFSecurity"))) {
bw.write("{" + keyStr + body + "}");
System.out.println("File written Successfully");
}
} catch (IOException io) {
io.printStackTrace();
} finally {
try {
if (bw != null) {
bw.close();
}
} catch (Exception ex) {
System.out.println("Error in closing the BufferedWriter" + ex);
}
}
}
private static void GetRestObject(JSONObject jsonObject) {
String restReq = "{" + reqStr;
StringBuilder sb1 = new StringBuilder();
for (Object key : jsonObject.keySet()) {
//if Key is not Request, get the containder body
String keyStr = (String) key;
if (!(keyStr.equalsIgnoreCase("Request"))) {
JSONObject itemBody = (JSONObject) jsonObject.get(keyStr);
System.out.println("Key requestBody " + key);
System.out.println("KeyString after comparison " + keyStr);
System.out.println("KeyString body " + itemBody);
sb1.append(itemBody);
}
}
}
}
}
{
"Security": {
"UsernameToken": {
"Username": "username",
"Password": "password"
},
"UPSServiceAccessToken": {
"AccessLicenseNumber": "AccessKey01"
}
},
"XAVRequest": {
"Request": {
"RequestOption": "1",
"TransactionReference": {
"CustomerContext": "Verify that an XAV request with an Address Line 1 element returns a successful response.",
"TransactionIdentifier": ""
}
},
"RegionalRequestIndicator": "",
"MaximumListSize": "10",
"AddressKeyFormat": {
"ConsigneeName": "RITZ CAMERA CENTERS-1749",
"BuildingName": "Innoplex",
"AddressLine": [
"26601 ALISO CREEK ROAD",
"STE D",
"ALISO VIEJO TOWN CENTER"
],
"Region": "ROSWELL,GA,30075-1521",
"PoliticalDivision2": "ALISO VIEJO",
"PoliticalDivision1": "CA",
"PostcodePrimaryLow": "92656",
"PostcodeExtendedLow": "1521",
"Urbanization": "porto arundal",
"CountryCode": "US"
}
}
}
I am trying to read values out of the Security container and the Request container into seperate variables and then re-write the file without the Security and Request containers. The final file should look like this:
{
"XAVRequest": {
"RegionalRequestIndicator": "",
"MaximumListSize": "10",
"AddressKeyFormat": {
"ConsigneeName": "RITZ CAMERA CENTERS-1749",
"BuildingName": "Innoplex",
"AddressLine": [
"26601 ALISO CREEK ROAD",
"STE D",
"ALISO VIEJO TOWN CENTER"
],
"Region": "ROSWELL,GA,30075-1521",
"PoliticalDivision2": "ALISO VIEJO",
"PoliticalDivision1": "CA",
"PostcodePrimaryLow": "92656",
"PostcodeExtendedLow": "1521",
"Urbanization": "porto arundal",
"CountryCode": "US"
}
}
The problem that I am running into is that the base name (in this case XAVRequest) will not always be the same. So I need the file to keep the base name, read the elements that I mention before, store them in variables, and then write the remaining objects. I am running into issues. Here is what I have so far:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package tester;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class Tester {
static String username, password, accesskey, reqOption = "", reqStr;
@SuppressWarnings("unchecked")
public static void main(String[] args) {
JSONParser jsonParser = new JSONParser();
Object obj;
try (FileReader reader = new FileReader("14771_req.rest.json")) {
//Read JSON file
obj = jsonParser.parse(reader);
JSONObject jsonObject = (JSONObject) obj;
//Handle the security object
HandleSecurityObject(jsonObject);
//Handle the object Body
JSONObject reqBody = HandleRequestObject(jsonObject);
//Remove the Request Container and write the file new file
GetRestObject(reqBody;
} catch (FileNotFoundException e) {
System.out.println("Could not find the reference file");
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}
private static void printJsonObject(JSONObject sec) {
for (Object key : sec.keySet()) {
//based on you key types
String keyStr = (String) key;
Object keyvalue = sec.get(keyStr);
switch (keyStr) {
case "AccessLicenseNumber":
accesskey = (String) keyvalue;
// System.out.println(accesskey);
break;
case "Username":
username = (String) keyvalue;
// System.out.println(username);
break;
case "Password":
password = (String) keyvalue;
// System.out.println(password);
break;
case "RequestOption":
reqOption = (String) keyvalue;
// System.out.println(reqOption);
break;
}
if (keyvalue instanceof JSONObject) {
printJsonObject((JSONObject) keyvalue);
}
}
}
private static void HandleSecurityObject(JSONObject jsonObject) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
//1. Get security header information and store in variable try 'Security' first
JSONObject sec = (JSONObject) jsonObject.get("Security");
if (sec.isEmpty()) {
sec = (JSONObject) jsonObject.get("UPSSecurity"); //try 'UPSSecurity'
}
System.out.println("Security object: " + sec);
printJsonObject(sec);
// return sec.toString();
}
private static JSONObject HandleRequestObject(JSONObject jsonObject) {
JSONObject reqBody = null;
for (Object key : jsonObject.keySet()) {
//Read key, act if not Security Container
String keyStr = (String) key;
if (!(keyStr.equalsIgnoreCase("Security")) && !(keyStr.equalsIgnoreCase("UPPFSecurity"))) {
System.out.println("Key After comparison " +key);
reqStr = keyStr;
System.out.println("KeyString after comparison " + keyStr);
JSONObject body = (JSONObject) jsonObject.get(keyStr);
System.out.println("Body" + body);
reqBody = body;
System.out.println("reqBody" + reqBody);
}
}
return reqBody;
}
private static void writeNewRestFile(String keyStr, JSONObject body) {
BufferedWriter bw = null;
try {
File file = new File("14771_new_req.rest.json");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file);
bw = new BufferedWriter(fw);
if (!(keyStr.equalsIgnoreCase("Security")) || !(keyStr.equalsIgnoreCase("UPPFSecurity"))) {
bw.write("{" + keyStr + body + "}");
System.out.println("File written Successfully");
}
} catch (IOException io) {
io.printStackTrace();
} finally {
try {
if (bw != null) {
bw.close();
}
} catch (Exception ex) {
System.out.println("Error in closing the BufferedWriter" + ex);
}
}
}
private static void GetRestObject(JSONObject jsonObject) {
String restReq = "{" + reqStr;
StringBuilder sb1 = new StringBuilder();
for (Object key : jsonObject.keySet()) {
//if Key is not Request, get the containder body
String keyStr = (String) key;
if (!(keyStr.equalsIgnoreCase("Request"))) {
JSONObject itemBody = (JSONObject) jsonObject.get(keyStr);
System.out.println("Key requestBody " + key);
System.out.println("KeyString after comparison " + keyStr);
System.out.println("KeyString body " + itemBody);
sb1.append(itemBody);
}
}
}
}
}