97 lines
2.8 KiB
Java
97 lines
2.8 KiB
Java
/*
|
|
* Copyright (C) 2010 Google Inc.
|
|
*
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
*/
|
|
|
|
package com.google.gson.jf;
|
|
|
|
import com.google.gson.GsonBuilder;
|
|
import com.google.gson.Strictness;
|
|
import com.google.gson.reflect.TypeToken;
|
|
import com.google.gson.stream.JsonWriter;
|
|
import org.junit.Test;
|
|
|
|
import java.io.IOException;
|
|
import java.io.StringWriter;
|
|
import java.util.Arrays;
|
|
import java.util.List;
|
|
|
|
import static com.google.common.truth.Truth.assertThat;
|
|
|
|
/**
|
|
* @author Jesse Wilson
|
|
*/
|
|
public final class CommentsTest {
|
|
|
|
/**
|
|
* Test for issue 212.
|
|
*/
|
|
@Test
|
|
public void testParseComments() {
|
|
String json = "[\n"
|
|
+ " // this is a comment\n"
|
|
+ " \"a\",\n"
|
|
+ " /* this is another comment */\n"
|
|
+ " \"b\",\n"
|
|
+ " # this is yet another comment\n"
|
|
+ " \"c\"\n"
|
|
+ "]";
|
|
|
|
List<String> abc = new GsonBuilder().setStrictness(Strictness.LENIENT).create().fromJson(json, new TypeToken<List<String>>() {}.getType());
|
|
assertThat(abc).isEqualTo(Arrays.asList("a", "b", "c"));
|
|
}
|
|
|
|
@Test
|
|
public void testWriteComments() throws IOException {
|
|
String expectedJson = "// comment at file head\n"
|
|
+ "[\n"
|
|
+ " // comment directly after context\n"
|
|
+ " \"a\",\n"
|
|
+ " // comment before context\n"
|
|
+ " {\n"
|
|
+ " // comment directly after object context\n"
|
|
+ " \"b\": \"c\",\n"
|
|
+ " // comment before name, after value\n"
|
|
+ " \"d\": \"e\"\n"
|
|
+ " }\n"
|
|
+ " // comment before context end\n"
|
|
+ "]\n"
|
|
+ "// comment behind the object";
|
|
|
|
StringWriter sw = new StringWriter();
|
|
JsonWriter jw = new JsonWriter(sw);
|
|
jw.setStrictness(Strictness.LENIENT);
|
|
jw.setIndent(" ");
|
|
|
|
jw.comment("comment at file head")
|
|
.beginArray()
|
|
.comment("comment directly after context")
|
|
.value("a")
|
|
.comment("comment before context")
|
|
.beginObject()
|
|
.comment("comment directly after object context")
|
|
.name("b").value("c")
|
|
.comment("comment before name, after value")
|
|
.name("d").value("e")
|
|
.endObject()
|
|
.comment("comment before context end")
|
|
.endArray()
|
|
.comment("comment behind the object");
|
|
|
|
jw.close();
|
|
assertThat(sw.toString()).isEqualTo(expectedJson);
|
|
sw.close();
|
|
}
|
|
}
|