0

I tried to use Gson and org.json as the examples. I tried Commons Text as well, but I doesn't work for me, when I import the library manually (I not allowed to use Maven). So I decided to search for another solution.

NoClassDefFoundError: org/apache/commons/text/StringEscapeUtils

I need to escape an Array to Json this way. Especially Ó, ó or any Latin-1 character( Not escape ", just escape what is in "&%$/"Helló" ). Original message: Helló / // \ "WÓRLD"

{"token":"045-245","message":"Helló / // \\ \"WÓRLD\" "}

to

{"token":"045-245","message":"Hell\u00F3 / // \\ \"W\u00D3RLD\" "}

This what I get when I use:

Gson

JsonObject json = new JsonObject();
json.addProperty("token", "045-245");
json.addProperty("message", "Helló WÓRLD");
String payload = new Gson().toJson(json);
System.out.println(payload);

Result:

{"token":"045-245","message":"Helló WÓRLD"}

org.json

JSONObject jsonObject = new JSONObject();        
jsonObject.put("token", "045-245");
jsonObject.put("message", "Helló WÓRLD");
System.out.println(jsonObject.toString());

Result:

{"message":"Helló WÓRLD","token":"045-245"}
Alberto Sanchez
  • 109
  • 1
  • 1
  • 11
  • 1
    Gson does not support this (see https://stackoverflow.com/questions/43091804/gson-unicode-characters-conversion-to-unicode-character-codes for a workaround). But Jackson does! See https://stackoverflow.com/questions/23121765/write-objectnode-to-json-string-with-utf-8-characters-to-escaped-ascii – dnault Jun 03 '19 at 21:05
  • Possible duplicate of [Write ObjectNode to JSON String with UTF-8 Characters to Escaped ASCII](https://stackoverflow.com/questions/23121765/write-objectnode-to-json-string-with-utf-8-characters-to-escaped-ascii) – dnault Jun 03 '19 at 21:06
  • @dnault Thanks, but do need I to use Maven ? I donwloaded the last Jackson version, but Netbeans can't manage `ObjectMapper mapper = new ObjectMapper()`. Because as I ask, I am not allowed to use Maven. – Alberto Sanchez Jun 03 '19 at 21:40
  • You just need to have Jackson on your classpath. – David Conrad Jun 04 '19 at 15:32

1 Answers1

0

Thanks to @dnault I found Jackson Json Library. I needed to import com.fasterxml.jackson.core, com.fasterxml.jackson.databind. I imported com.fasterxml.jackson.annotations as well, for no problems on JDK 8.

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

public class Foo {

    ObjectMapper mapper = new ObjectMapper();
    mapper.getFactory().configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true);
    ObjectNode node = mapper.getNodeFactory().objectNode();
    node.put("token", "045-245");
    node.put("message", "Helló / // \\ \"WÓRLD\" ");
    System.out.println(mapper.writeValueAsString(node));

}

Output:

{"token":"045-245","message":"Hell\u00F3 / // \\ \"W\u00D3RLD\" "}
Alberto Sanchez
  • 109
  • 1
  • 1
  • 11