Use build-in function to write field name in JsonXContentGenerator#writeRawField

The #writeRawField method forcefully writes a `,` spearator expecting a raw field
to never start as the first value in an object.

Closes #5514
This commit is contained in:
Simon Willnauer 2014-03-24 14:19:34 +01:00
parent 21e2dfb6b1
commit c2e6aa273d
2 changed files with 32 additions and 3 deletions

View File

@ -300,9 +300,8 @@ public class JsonXContentGenerator implements XContentGenerator {
}
protected void writeObjectRaw(String fieldName, BytesReference content, OutputStream bos) throws IOException {
generator.writeRaw(", \"");
generator.writeRaw(fieldName);
generator.writeRaw("\" : ");
generator.writeFieldName(fieldName);
generator.writeRaw(':');
flush();
content.writeTo(bos);
}

View File

@ -20,6 +20,7 @@
package org.elasticsearch.common.xcontent.builder;
import com.google.common.collect.Lists;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.io.FastCharArrayWriter;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.xcontent.XContentBuilder;
@ -29,6 +30,7 @@ import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.test.ElasticsearchTestCase;
import org.junit.Test;
import java.io.IOException;
import java.util.*;
import static org.elasticsearch.common.xcontent.XContentBuilder.FieldCaseConversion.CAMELCASE;
@ -80,6 +82,34 @@ public class XContentBuilderTests extends ElasticsearchTestCase {
assertThat(writer.toStringTrim(), equalTo("{\"test\":\"value\"}"));
}
@Test
public void testRaw() throws IOException {
{
XContentBuilder xContentBuilder = XContentFactory.contentBuilder(XContentType.JSON);
xContentBuilder.startObject();
xContentBuilder.rawField("foo", new BytesArray("{\"test\":\"value\"}"));
xContentBuilder.endObject();
assertThat(xContentBuilder.bytes().toUtf8(), equalTo("{\"foo\":{\"test\":\"value\"}}"));
}
{
XContentBuilder xContentBuilder = XContentFactory.contentBuilder(XContentType.JSON);
xContentBuilder.startObject();
xContentBuilder.field("test", "value");
xContentBuilder.rawField("foo", new BytesArray("{\"test\":\"value\"}"));
xContentBuilder.endObject();
assertThat(xContentBuilder.bytes().toUtf8(), equalTo("{\"test\":\"value\",\"foo\":{\"test\":\"value\"}}"));
}
{
XContentBuilder xContentBuilder = XContentFactory.contentBuilder(XContentType.JSON);
xContentBuilder.startObject();
xContentBuilder.field("test", "value");
xContentBuilder.rawField("foo", new BytesArray("{\"test\":\"value\"}"));
xContentBuilder.field("test1", "value1");
xContentBuilder.endObject();
assertThat(xContentBuilder.bytes().toUtf8(), equalTo("{\"test\":\"value\",\"foo\":{\"test\":\"value\"},\"test1\":\"value1\"}"));
}
}
@Test
public void testSimpleGenerator() throws Exception {
XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);