jdereg / json-io

Convert Java to JSON. Convert JSON to Java. Pretty print JSON. Java JSON serializer. Deep copy Java object graphs.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Encoding Bug for JsonIo.toJson("πŸ™ŠπŸ™‰πŸ™ˆ", null)?

raubv0gel opened this issue Β· comments

Is this an encoding bug in JsonIo.toJson()?

Using String overloading JsonIo.toJson()
grafik

Using OutputStream overloading JsonIo.toJson()
grafik

I’m using com.cedarsoftware:json-io:4.19.9.

Looking into this.

@jdereg, pardon, but do you have any updates on this issue?

Found the issues - there are two of them, one yours, one json-io. The json-io issue has an easy work around (I'll put a fix anyway). This particular method advertises that you can pass in null for WriteOptions. Turns out that is not the case and you get an NPE.

So add a proper WriteOptions at the end (instead of null for now), like this:
JsonIo.toString(baos, "πŸ™ŠπŸ™‰πŸ™ˆ", new WriteOptionsBuilder().build());

Now, it will still fail for you because toByteArray() on ByteArray does not support the syntax you are using. You have to convert the ByteArrayOutputStream to a byte[] first, and then create the String from that byte[].

@Test
void testUnicodeChars() throws Exception
{
    String monkeys = "\uD83D\uDE4A\uD83D\uDE49\uD83D\uDE48";
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    JsonIo.toJson(baos, monkeys, new WriteOptionsBuilder().build());
    String json = baos.toString();    // Good
    System.out.println("json = " + json);
    // String json = new String(baos.toByteArray(), StandardCharsets.UTF_8);   // inefficient
    // String json = baos.toString(StandardCharsets.UTF_8);   // invalid
}

So this will get you going now. I have a fix coming out for the NPE on null writeOptions.