0

I have this JSON flat file and I need to change the value of clientCode

{
  "clientNumber": "Test",
  "clientCode": "12345",
  "clientReference": "JSON Testing",
  "billingCode":"90code",
  "clienttructure": "new, test, Java",
  "site": "sampleStore",
  "siteDestination": "EU",
}

I tried to change clientCode value and check the return of the method.

I'm Using Java

String jsonName = "clientCode ";
String jsonValue = "new Value";
String JSONSource = path;


public String put(String jsonName, String jsonValue, String JSONSource) {
        String jsonString = null;

        try {
            Object obj = parser.parse(new FileReader(JSONSource));
            org.json.simple.JSONObject jsonObject = (org.json.simple.JSONObject) obj;

            jsonObject.put(jsonName, jsonValue);

            jsonString = jsonObject.toJSONString();


        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return jsonString;
    }

Actual output is:

{ "billingCode":"90code", "clientCode": "new Value","clientNumber": "Test","clientReference": "JSON Testing",.....}

Expected output should be :

{
  "clientNumber": "Test",
  "clientCode": "new Value",
  "clientReference": "JSON Testing",
  "billingCode":"90code",
  "clienttructure": "new, test, Java",
  "site": "sampleStore",
  "siteDestination": "EU",
}
Rogbi
  • 9
  • 1
  • 3
  • 6
  • 4
    Is there a reason why you need the output in a specific order? – brandonx Apr 09 '19 at 01:15
  • You did not mention the API you are using. – SedJ601 Apr 09 '19 at 01:16
  • 2
    Complementing @brandonx comment, following the [RFC 7159](http://www.rfc-editor.org/rfc/rfc7159.txt), *an object is an **unordered** collection of zero or more value/pairs *, so I don't know if your requirement really makes sense – nortontgueno Apr 09 '19 at 01:17
  • If you really need to keep the order and formatting, a string replacement using a regular expression may also be an option (although not really a recommended way to process JSON). – Michael Butscher Apr 09 '19 at 01:18
  • @all just want to make the formatting output so that other developer in our team can easily read the json file, also it will be used for our logging. – Rogbi Apr 09 '19 at 01:25
  • Maybe https://stackoverflow.com/questions/4105795/pretty-print-json-in-java – Scary Wombat Apr 09 '19 at 01:28

1 Answers1

0

Try this...

JSONObject jsonobject =  new JSONObject(response);
jsonobject .remove("clientCode");

JSONObject updateValue = new JSONObject(updateValue);
String UpdatedValue = updateValue.getString("clientCode");
jsonobject .put("clientCode", UpdatedValue);
Community
  • 1
  • 1
Rajasimman R
  • 496
  • 4
  • 14