|
18 | 18 | package org.msgpack.type; |
19 | 19 |
|
20 | 20 | import java.util.Arrays; |
| 21 | +import java.nio.ByteBuffer; |
| 22 | +import java.nio.charset.Charset; |
| 23 | +import java.nio.charset.CharacterCodingException; |
| 24 | +import java.nio.charset.CharsetDecoder; |
| 25 | +import java.nio.charset.CodingErrorAction; |
| 26 | +import java.nio.charset.MalformedInputException; |
21 | 27 |
|
22 | 28 | abstract class AbstractRawValue extends AbstractValue implements RawValue { |
23 | 29 | public ValueType getType() { |
@@ -56,7 +62,24 @@ public String toString() { |
56 | 62 | } |
57 | 63 |
|
58 | 64 | public StringBuilder toString(StringBuilder sb) { |
59 | | - String s = getString(); |
| 65 | + String s; |
| 66 | + if(getClass() == StringRawValueImpl.class) { |
| 67 | + // StringRawValueImpl.getString never throws exception |
| 68 | + s = getString(); |
| 69 | + } else { |
| 70 | + // don't throw encoding error exception |
| 71 | + // ignore malformed bytes |
| 72 | + CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder(). |
| 73 | + onMalformedInput(CodingErrorAction.IGNORE). |
| 74 | + onUnmappableCharacter(CodingErrorAction.IGNORE); |
| 75 | + try { |
| 76 | + s = decoder.decode(ByteBuffer.wrap(getByteArray())).toString(); |
| 77 | + } catch (CharacterCodingException ex) { |
| 78 | + // never comes here |
| 79 | + s = new String(getByteArray()); |
| 80 | + } |
| 81 | + } |
| 82 | + |
60 | 83 | sb.append("\""); |
61 | 84 | for(int i=0; i < s.length(); i++) { |
62 | 85 | char ch = s.charAt(i); |
@@ -102,6 +125,7 @@ public StringBuilder toString(StringBuilder sb) { |
102 | 125 | } |
103 | 126 | } |
104 | 127 | sb.append("\""); |
| 128 | + |
105 | 129 | return sb; |
106 | 130 | } |
107 | 131 |
|
|
0 commit comments