इस लेखक के रूप में कार्यान्वित किया जाता है के साथ की आवश्यकता है। मैं इसे पाठक के रूप में कल्पना नहीं कर सका। काम के लिए काफी भारी लेकिन काफी विस्तार योग्य।
String multilineJson = "{\n" +
"prop1 = \"value1\",\n" +
"prop2 = \"multi line\n" +
"value2\"\n" +
"}\n";
String multilineJsonExpected = "{\n" +
"prop1 = \"value1\",\n" +
"prop2 = \"multi line\\nvalue2\"\n" +
"}\n";
StringWriter sw = new StringWriter();
JsonProcessor jsonProcessor = new JsonProcessor(sw);
jsonProcessor.write(multilineJson);
assertEquals(multilineJsonExpected, sw.toString());
कार्यान्वयन
public class JsonProcessor extends FilterWriter {
private char[] curr;
private int currIdx;
private boolean doubleQuoted;
public JsonProcessor(Writer out) {
super(out);
}
@Override
public void write(String str) throws IOException {
char[] arr = str.toCharArray();
write(arr, 0, arr.length);
}
@Override
synchronized public void write(char[] cbuf, int off, int len) throws IOException {
curr = Arrays.copyOfRange(cbuf, off, len - off);
for (currIdx = 0; currIdx < curr.length; currIdx++) {
processChar();
}
}
private void processChar() throws IOException {
switch (currentChar()) {
case '"':
processDoubleQuotesSymbol();
break;
case '\n':
case '\r':
processLineBreakSymbol();
break;
default:
write(currentChar());
break;
}
}
private void processDoubleQuotesSymbol() throws IOException {
doubleQuoted = !doubleQuoted;
write('"');
}
private void processLineBreakSymbol() throws IOException {
if (doubleQuoted) {
write('\\');
write('n');
if (lookAhead() == '\n' || lookAhead() == '\r') {
currIdx++;
}
} else {
write(currentChar());
}
}
private char currentChar() {
return curr[currIdx];
}
private char lookAhead() {
if (currIdx >= curr.length) {
return 0;
}
return curr[currIdx + 1];
}
}
स्रोत
2016-06-15 13:51:28
{ "testCases" : { "case.1" : { "scenario" : "this the case 1.", "result" : "this is a very long line which is not easily readble. so i would like to write it in multiple lines. but, i do NOT require any new lines in the output. I need to split the string value in this input file only. such that I don't require to slide the horizontal scroll again and again while verifying the correctness of the statements. the prev line, I have shown, without splitting just to give a feel of my problem" } } } }
[JSON में बहुपंक्ति तार] (http के – user2409155संभव डुप्लिकेट का उपयोग कर सकते में: // stackoverflow .com/प्रश्न/2392766/मल्टीलाइन-स्ट्रिंग्स-इन-जेसन) –
मुझे लगता है कि यह सीरियलाइज्ड JSON फ़ाइल की पठनीयता और लोड किए गए डेटा में लाइनब्रेक्स के बारे में _not_ के बारे में अधिक नहीं है (इस प्रकार, JSON में [मल्टीलाइन स्ट्रिंग्स का डुप्लिकेट नहीं) http://stackoverflow.com/q/2392766/703040))। इसके बारे में सोचें कि JSON को कॉन्फ़िगरेशन फ़ाइल के रूप में उपयोग करने की तरह, जहां आपके पास लंबी स्ट्रिंग है और, पठनीयता के लिए, किसी पाठ संपादक के माध्यम से इसे संपादित करने के मामले में स्ट्रिंग को हार्ड-लपेटना उपयोगी होता है। – zashu