0

I create JsonObject and JsonArray as following:

JSONObject jObj = new JSONObject();
jObj.put("path", "dfds/g");
jObj.put("etag", "dfdsfsd");
jObj.put("size_bytes", 123);
JSONArray list = new JSONArray();
list.add(jObj);
String s = list.toJSONString();

The result I get:

[{"size_bytes":123,"etag":"dfdsfsd","path":"dfds\/g"}]
  1. I expect the path component to be "path":"dfds\g", not dfds\/g
  2. I need the field to be in order as I they in the code, but they are not as I expected:path, etag, size_bytes I`ll be glad to get an advices how to solve the above issues
YAKOVM
  • 9,805
  • 31
  • 116
  • 217
  • The order of elements in your object should not matter, you should be able to convert to and from `JSON` regardless. The `backslash` is appearing to escape the `forwardslash` – Blake Yarbrough Oct 15 '15 at 15:06

2 Answers2

4

The Json encoder is escaping your forward slash which is why you're getting \/. This is completely legal syntax and not something to worry about.

You shouldn't need to worry about ordering inside a Json string, fields are inherently not ordered and relying on this could well lead to issues for you in the future.

tddmonkey
  • 20,798
  • 10
  • 58
  • 67
  • The json string is sent to other process it expect the path to be without '\': Can`t read 'dfds\/g', expects 'dfds\g' – YAKOVM Oct 15 '15 at 15:07
  • Use a JSON decoder rather than trying to do it by hand would be my best suggestion – tddmonkey Oct 15 '15 at 15:14
  • I form json string and send it to other process. that process is 3 party. I just know it expect path without '\' – YAKOVM Oct 15 '15 at 15:15
  • Have you actually tried sending it? If the 3rd party is being sensible they will be able to handle this just fine. – tddmonkey Oct 15 '15 at 15:24
  • I sent it - it didn`t work properly. Looks that there the order of tags and backslash are important – YAKOVM Oct 15 '15 at 15:25
  • 2
    Ok so the 3rd party, no matter what they say are *not* using a JSON format at all. Can you have them fix this at their end? – tddmonkey Oct 15 '15 at 15:31
0

If you absolutely MUST remove the forward slash from your string then you can do this:

s = s.replace("\\/", "/");

See String replace a Backslash for more information.

I recommend not doing this in this circumstance. Instead you should parse the String using one of the many JSON parsing libraries.

Here is an example of this in action with your sample String:

public static void main(String[] args){
    String s = "[{\"size_bytes\":123,\"etag\":\"dfdsfsd\",\"path\":\"dfds\\/g\"}]";
    
    System.out.println(s);
    
    s = s.replace("\\/", "/");
    
    System.out.println(s);
}

Output:

[{"size_bytes":123,"etag":"dfdsfsd","path":"dfds\/g"}]

[{"size_bytes":123,"etag":"dfdsfsd","path":"dfds/g"}]

Community
  • 1
  • 1
Blake Yarbrough
  • 2,286
  • 1
  • 20
  • 36