com.dslplatform.json.runtime.Settings Java Examples

The following examples show how to use com.dslplatform.json.runtime.Settings. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ArrayChecksTest.java    From dsl-json with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public ArrayChecksTest() {
	ArrayFormatDescription<MyClass, MyClass> description = ArrayFormatDescription.create(
			MyClass.class,
			MyClass::new,
			new JsonWriter.WriteObject[] {
					Settings.<MyClass, Integer>createArrayEncoder(c -> c.x, dslJson, int.class),
					Settings.<MyClass, String>createArrayEncoder(c -> c.s, dslJson, String.class),
					Settings.<MyClass, Long>createArrayEncoder(c -> c.y, NumberConverter.LONG_WRITER)
			},
			new JsonReader.BindObject[] {
					Settings.<MyClass, Integer>createArrayDecoder((c, v) -> c.x = v, NumberConverter.INT_READER),
					Settings.<MyClass, String>createArrayDecoder((c, v) -> c.s = v, dslJson, String.class),
					Settings.<MyClass, Long>createArrayDecoder((c, v) -> c.y = v, dslJson, long.class)
			}
	);
	dslJson.registerBinder(MyClass.class, description);
	dslJson.registerReader(MyClass.class, description);
}
 
Example #2
Source File: BindingChecksTest.java    From dsl-json with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public BindingChecksTest() {
	ObjectFormatDescription<MyClass, MyClass> description = ObjectFormatDescription.create(
			MyClass.class,
			MyClass::new,
			new JsonWriter.WriteObject[0],
			new DecodePropertyInfo[] {
					Settings.<MyClass, Integer>createDecoder((c, v) -> c.x = v, "x", dslJson, false, true, 0, false, int.class),
					Settings.<MyClass, String>createDecoder((c, v) -> c.s = v, "s", dslJson, false, false, 1, false, StringConverter.READER),
					Settings.<MyClass, Long>createDecoder((c, v) -> c.y = v, "y", dslJson, false, true, 2, false, long.class)
			},
			dslJson,
			false
	);
	dslJson.registerBinder(MyClass.class, description);
	dslJson.registerReader(MyClass.class, description);
}
 
Example #3
Source File: OptionalTest.java    From dsl-json with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void lazyOptionalResolution() throws IOException {
	DslJson<Object> lazy = new DslJson<Object>(Settings.basicSetup());
	JsonReader.ReadObject decoder = lazy.tryFindReader(new TypeDefinition<Optional<LocalDate>>() {}.type);
	JsonWriter.WriteObject encoder = lazy.tryFindWriter(new TypeDefinition<Optional<LocalDate>>() {}.type);
	Assert.assertNotNull(decoder);
	Assert.assertNotNull(encoder);
	JsonWriter writer = lazy.newWriter();
	LocalDate date = LocalDate.of(2018, 7, 26);
	encoder.write(writer, Optional.of(date));
	Assert.assertEquals("\"2018-07-26\"", writer.toString());
	JsonReader<Object> reader = lazy.newReader(writer.toByteArray());
	reader.read();
	Optional<LocalDate> result = (Optional<LocalDate>) decoder.read(reader);
	Assert.assertEquals(date, result.get());
}
 
Example #4
Source File: BuilderTest.java    From dsl-json with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public BuilderTest() {
	ObjectFormatDescription<Immutable.Builder, Immutable> description = new ObjectFormatDescription<Immutable.Builder, Immutable>(
			Immutable.class,
			Immutable.Builder::new,
			Immutable.Builder::build,
			new JsonWriter.WriteObject[] {
					Settings.<Immutable, Integer>createEncoder(c -> c.x, "x", json, int.class),
					Settings.<Immutable, Long>createEncoder(c -> c.y, "y", json, long.class)
			},
			new DecodePropertyInfo[] {
					Settings.<Immutable.Builder, Integer>createDecoder(Immutable.Builder::x, "x", json, int.class),
					Settings.<Immutable.Builder, Long>createDecoder(Immutable.Builder::y, "y", json, long.class)
			},
			json,
			true
	);
	json.registerReader(Immutable.class, description);
	json.registerWriter(Immutable.class, description);
}
 
Example #5
Source File: EnumTest.java    From dsl-json with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testCustomNamesWithUnknown() throws IOException {
	DslJson<Object> dslJsonUnknown = new DslJson<>(
			Settings.withAnalyzers(true, true)
					.includeServiceLoader()
					.unknownNumbers(JsonReader.UnknownNumberParsing.LONG_AND_DOUBLE));
	EnumHolderUnknown model = new EnumHolderUnknown();
	model.enum1 = EnumWithCustomNames1.TEST_A1;
	model.enum2 = EnumWithCustomNamesObject.DOUBLE;
	model.enumList1 = Arrays.asList(EnumWithCustomNames1.values());
	model.enumList2 = Arrays.asList(EnumWithCustomNamesObject.values());

	ByteArrayOutputStream os = new ByteArrayOutputStream();
	dslJsonUnknown.serialize(model, os);
	byte[] json = os.toByteArray();

	Assertions.assertThat(new String(json))
			.isEqualTo("{\"enumList2\":[\"\",0,0.0],\"enumList1\":[\"a1\",\"a2\",\"a3\"]," +
					"\"enum1\":\"a1\",\"enum2\":0.0}");

	EnumHolderUnknown result = dslJsonUnknown.deserialize(EnumHolderUnknown.class, json, json.length);
	Assertions.assertThat(result).isEqualToComparingFieldByFieldRecursively(model);
}
 
Example #6
Source File: GenericTest.java    From dsl-json with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void unboundedCollections() throws IOException {
	DslJson<Object> dslJsonUnknown = new DslJson<>(Settings.withRuntime().allowArrayFormat(true).includeServiceLoader());
	UnboundedCollections model = new UnboundedCollections();
	Map map = new HashMap<>();
	map.put("x", BigDecimal.valueOf(505, 1));
	model.map = map;
	Set set = new HashSet<>();
	set.add(Double.POSITIVE_INFINITY);
	set.add(2.2);
	model.set = set;
	model.list = Arrays.asList("xXx", null, "xyz");

	ByteArrayOutputStream os = new ByteArrayOutputStream();
	dslJsonUnknown.serialize(model, os);

	UnboundedCollections result = dslJsonUnknown.deserialize(UnboundedCollections.class, os.toByteArray(), os.size());

	assertThat(result).isEqualToComparingFieldByFieldRecursively(model);
}
 
Example #7
Source File: DateTest.java    From dsl-json with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void twoDateTimes() throws IOException {
	ModelLDT model = new ModelLDT();
	model.date = LocalDateTime.of(2018, 12, 25, 1, 0);
	model.now = LocalDateTime.now();
	ByteArrayOutputStream os = new ByteArrayOutputStream();
	DslJson<Object> dslJson = new DslJson<>(Settings.withRuntime().skipDefaultValues(true));
	dslJson.serialize(model, os);
	byte[] bytes = os.toByteArray();
	System.out.println(new String(bytes));
	for (int i = 0; i < 1000; i++) {
		ModelLDT result = dslJson.deserialize(ModelLDT.class, bytes, bytes.length);
		Assert.assertEquals(model.date, result.date);
		Assert.assertEquals(model.now, result.now);
	}
}
 
Example #8
Source File: DateTest.java    From dsl-json with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void twoOffsets() throws IOException {
	ModelODT model = new ModelODT();
	model.date = OffsetDateTime.of(2018, 12, 25, 1, 0, 0, 0, ZoneOffset.UTC);
	model.now = OffsetDateTime.now();
	ByteArrayOutputStream os = new ByteArrayOutputStream();
	DslJson<Object> dslJson = new DslJson<>(Settings.withRuntime().skipDefaultValues(true));
	dslJson.serialize(model, os);
	byte[] bytes = os.toByteArray();
	System.out.println(new String(bytes));
	for (int i = 0; i < 1000; i++) {
		ModelODT result = dslJson.deserialize(ModelODT.class, bytes, bytes.length);
		Assert.assertEquals(model.date, result.date);
		Assert.assertEquals(model.now, result.now);
	}
}
 
Example #9
Source File: GenericTest.java    From dsl-json with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testRawSignatureWithRuntime() throws IOException {
	DslJson<Object> dslJsonUnknown = new DslJson<>(Settings.withRuntime().allowArrayFormat(true).includeServiceLoader());
	ByteArrayOutputStream os = new ByteArrayOutputStream();
	GenericModel model = generateModel();
	try {
		dslJson.serialize(model, os);
		Assert.fail("Expecting exception");
	} catch (ConfigurationException ex) {
		Assert.assertTrue(ex.getMessage().contains("Unable to serialize provided object. Failed to find serializer"));
	}
	os.reset();
	dslJsonUnknown.serialize(model, os);

	Type type = new TypeDefinition<GenericModel<String, Double>>() {}.type;
	GenericModel<String, Double> result = (GenericModel<String, Double>) dslJsonUnknown.deserialize(type, os.toByteArray(), os.size());

	assertThat(result).isEqualToComparingFieldByFieldRecursively(model);
}
 
Example #10
Source File: GenericTest.java    From dsl-json with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testRawSignature() throws IOException {
	DslJson.Settings<Object> settings = new DslJson.Settings<>()
			.resolveReader(Settings.UNKNOWN_READER)
			.resolveWriter(Settings.UNKNOWN_WRITER)
			.allowArrayFormat(true)
			.includeServiceLoader();
	DslJson<Object> dslJsonUnknown = new DslJson<>(settings);
	ByteArrayOutputStream os = new ByteArrayOutputStream();
	GenericModel model = generateModel();
	try {
		dslJson.serialize(model, os);
		Assert.fail("Expecting exception");
	} catch (ConfigurationException ex) {
		Assert.assertTrue(ex.getMessage().contains("Unable to serialize provided object. Failed to find serializer"));
	}
	os.reset();
	dslJsonUnknown.serialize(model, os);

	Type type = new TypeDefinition<GenericModel<String, Double>>() {}.type;
	GenericModel<String, Double> result = (GenericModel<String, Double>) dslJsonUnknown.deserialize(type, os.toByteArray(), os.size());

	assertThat(result).isEqualToComparingFieldByFieldRecursively(model);
}
 
Example #11
Source File: StringsTest.java    From dsl-json with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void nullArrayPropertyWillThrow() throws IOException {
	Strings s = new Strings();
	s.s1 = "";
	DslJson<Object> dslJsonMinimal = new DslJson<>(Settings.basicSetup().skipDefaultValues(true));
	for (DslJson<Object> json : new DslJson[]{dslJson, dslJsonMinimal}) {
		try {
			dslJson.serialize(s, new ByteArrayOutputStream());
			Assert.fail("Expecting exception");
		} catch (ConfigurationException ex) {
			Assert.assertTrue(ex.getMessage().contains("Property 's3' is not allowed to be null"));
		}
	}
}
 
Example #12
Source File: StringsTest.java    From dsl-json with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void nullSimplePropertyWillThrow() throws IOException {
	DslJson<Object> dslJsonMinimal = new DslJson<>(Settings.basicSetup().skipDefaultValues(true));
	for (DslJson<Object> json : new DslJson[]{dslJson, dslJsonMinimal}) {
		try {
			dslJson.serialize(new Strings(), new ByteArrayOutputStream());
			Assert.fail("Expecting exception");
		} catch (ConfigurationException ex) {
			Assert.assertTrue(ex.getMessage().contains("Property 's1' is not allowed to be null"));
		}
	}
}
 
Example #13
Source File: DSL.java    From dsl-json with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static DslJson<Object> JSON() {
    if (json == null) {
        //Model converters will be loaded based on naming convention.
        //Previously it would be loaded through ServiceLoader.load,
        //which is still an option if dsljson.configuration name is specified.
        //DSL-JSON loads all services registered into META-INF/services
        //and falls back to naming based convention of package._NAME_DslJsonConfiguration if not found
        //basicSetup is Android friendly version of withRuntime (which avoids Java8 types)
        //It is enabled to support runtime analysis for stuff which is not registered by default
        //Annotation processor will run by default and generate descriptions for JSON encoding/decoding
        json = new DslJson<>(Settings.basicSetup().allowArrayFormat(true));
    }
    return json;
}
 
Example #14
Source File: DateTest.java    From dsl-json with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void sqlDateWillNotExplode() throws IOException {
	java.util.Date ud = new java.util.Date(119, 2, 10);
	SqlDate sql = new SqlDate();
	sql.date = new java.sql.Date(ud.getTime());
	DslJson<Object> dslJson = new DslJson<>(Settings.withRuntime());
	ByteArrayOutputStream os = new ByteArrayOutputStream();
	dslJson.serialize(sql, os);
	Assert.assertEquals("{\"date\":\"2019-03-10\"}", os.toString());
}
 
Example #15
Source File: DateTest.java    From dsl-json with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void nineDigitsInAOTClass() throws IOException {
	NineOT n = new NineOT();
	n.at = OffsetTime.parse("01:33:08.750431006Z");
	DslJson<Object> dslJson = new DslJson<>(Settings.withRuntime());
	ByteArrayOutputStream os = new ByteArrayOutputStream();
	dslJson.serialize(n, os);;
	Assert.assertEquals("{\"at\":\"01:33:08.750431006Z\"}", os.toString());
}
 
Example #16
Source File: DateTest.java    From dsl-json with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void nineDigitsInAODTClass() throws IOException {
	NineODT n = new NineODT();
	n.at = OffsetDateTime.parse("1930-09-04T00:03:48.750431006Z");
	DslJson<Object> dslJson = new DslJson<>(Settings.withRuntime());
	ByteArrayOutputStream os = new ByteArrayOutputStream();
	dslJson.serialize(n, os);;
	Assert.assertEquals("{\"at\":\"1930-09-04T00:03:48.750431006Z\"}", os.toString());
}
 
Example #17
Source File: OptionalTest.java    From dsl-json with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void externalConvertersWillTakePrecedanceOverCustomFactories() throws IOException {
	DslJson<Object> lazy = new DslJson<>(Settings.basicSetup().resolveReader(CUSTOM_READER).resolveWriter(CUSTOM_WRITER));
	JsonReader.ReadObject decoder = lazy.tryFindReader(new TypeDefinition<Optional<LocalDate>>() {}.type);
	JsonWriter.WriteObject encoder = lazy.tryFindWriter(new TypeDefinition<Optional<LocalDate>>() {}.type);
	Assert.assertNotNull(decoder);
	Assert.assertNotNull(encoder);
	encoder.write(lazy.newWriter(), Optional.empty());
	JsonReader rdr = lazy.newReader("null".getBytes(StandardCharsets.UTF_8));
	rdr.read();
	decoder.read(rdr);
}
 
Example #18
Source File: Example.java    From dsl-json with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static void main(String[] args) throws IOException {

		//Model converters will be loaded based on naming convention.
		//Previously it would be loaded through ServiceLoader.load,
		//which is still an option if dsljson.configuration name is specified.
		//DSL-JSON loads all services registered into META-INF/services
		//and falls back to naming based convention of package._NAME_DslJsonConfiguration if not found
		//Annotation processor will run by default and generate descriptions for JSON encoding/decoding
		//To include Jackson annotations dsljson.jackson=true must be passed to annotation processor
		//When conversion is not fully supported by compiler Settings.basicSetup() can be enabled to support runtime analysis
		//for features not registered by annotation processor. Currently it is enabled due to use of Set and Vector
		DslJson<Object> dslJson = new DslJson<>(Settings.basicSetup());

		Model instance = new Model();
		instance.string = "Hello World!";
		instance.integers = Arrays.asList(1, 2, 3);
		instance.decimals = new HashSet<>(Arrays.asList(BigDecimal.ONE, BigDecimal.ZERO));
		instance.uuids = new UUID[]{new UUID(1L, 2L), new UUID(3L, 4L)};
		instance.longs = new Vector<>(Arrays.asList(1L, 2L));
		instance.inheritance = new Model.ParentClass();
		instance.inheritance.a = 5;
		instance.inheritance.b = 6;
		instance.iface = new Model.WithCustomCtor(5, 6);
		instance.person = new ImmutablePerson("first name", "last name", 35);
		instance.states = Arrays.asList(Model.State.HI, Model.State.LOW);
		instance.jsonObject = new Model.JsonObjectReference(43, "abcd");
		instance.jsonObjects = Collections.singletonList(new Model.JsonObjectReference(34, "dcba"));
		instance.intList = new ArrayList<>(Arrays.asList(123, 456));
		instance.map = new HashMap<>();
		instance.map.put("abc", 678);
		instance.map.put("array", new int[] { 2, 4, 8});
		instance.factories = Arrays.asList(null, Model.ViaFactory.create("me", 2), Model.ViaFactory.create("you", 3), null);
		instance.builder = PersonBuilder.builder().firstName("first").lastName("last").age(42).build();

		ByteArrayOutputStream os = new ByteArrayOutputStream();
		dslJson.serialize(instance, os);
		System.out.println(os);

		ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
		//deserialization using Stream API
		Model deser = dslJson.deserialize(Model.class, is);

		System.out.println(deser.string);
	}
 
Example #19
Source File: Example.java    From dsl-json with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static void main(String[] args) throws IOException {

		//Model converters will be loaded based on naming convention.
		//Previously it would be loaded through ServiceLoader.load,
		//which is still an option if dsljson.configuration name is specified.
		//DSL-JSON loads all services registered into META-INF/services
		//and falls back to naming based convention of package._NAME_DslJsonConfiguration if not found
		//withRuntime is enabled to support runtime analysis for stuff which is not registered by default
		//Annotation processor will run by default and generate descriptions for JSON encoding/decoding
		DslJson<Object> dslJson = new DslJson<>(Settings.withRuntime().allowArrayFormat(true).includeServiceLoader());
		//writer should be reused. For per thread reuse use ThreadLocal pattern
		JsonWriter writer = dslJson.newWriter();

		Model instance = new Model();
		instance.string = "Hello World!";
		instance.number = 42;
		instance.integers = Arrays.asList(1, 2, 3);
		instance.decimals = new HashSet<>(Arrays.asList(BigDecimal.ONE, BigDecimal.ZERO));
		instance.uuids = new UUID[]{new UUID(1L, 2L), new UUID(3L, 4L)};
		instance.longs = new Vector<>(Arrays.asList(1L, 2L));
		instance.nested = Arrays.asList(new Model.Nested(), null);
		instance.inheritance = new Model.ParentClass();
		instance.inheritance.a = 5;
		instance.inheritance.b = 6;
		instance.iface = new Model.WithCustomCtor(5, 6);
		instance.person = new ImmutablePerson("first name", "last name", 35);
		instance.states = Arrays.asList(Model.State.HI, Model.State.LOW);
		instance.jsonObject = new Model.JsonObjectReference(43, "abcd");
		instance.jsonObjects = Collections.singletonList(new Model.JsonObjectReference(34, "dcba"));
		instance.time = LocalTime.of(12, 15);
		instance.times = Arrays.asList(null, LocalTime.of(8, 16));
		Model.Concrete concrete = new Model.Concrete();
		concrete.x = 11;
		concrete.y = 23;
		instance.abs = concrete;
		instance.absList = Arrays.<Model.Abstract>asList(concrete, null, concrete);
		instance.decimal2 = BigDecimal.TEN;
		instance.intList = new ArrayList<>(Arrays.asList(123, 456));
		instance.map = new HashMap<>();
		instance.map.put("abc", 678);
		instance.map.put("array", new int[] { 2, 4, 8});
		instance.factories = Arrays.asList(null, Model.ViaFactory.create("me", 2), Model.ViaFactory.create("you", 3), null);
		instance.builder = PersonBuilder.builder().firstName("first").lastName("last").age(42).build();
		instance.numbers = Arrays.asList(SpecialNumber.E, SpecialNumber.PI, SpecialNumber.ZERO);

		dslJson.serialize(writer, instance);

		//resulting buffer with JSON
		byte[] buffer = writer.getByteBuffer();
		//end of buffer
		int size = writer.size();
		System.out.println(writer);

		//deserialization using byte[] API
		Model deser = dslJson.deserialize(Model.class, buffer, size);

		System.out.println(deser.string);
	}
 
Example #20
Source File: Example.java    From dsl-json with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static void main(String[] args) throws IOException {

		//since annotation processor is disabled in pom.xml only reflection will be used.
		//even if annotation processor was not disabled, it would still run in reflection mode unless
		//.includeServiceLoader() is called on Settings
		DslJson<Object> dslJson = new DslJson<>(Settings.withRuntime()); //Runtime configuration needs to be explicitly enabled
		//writer should be reused. For per thread reuse use ThreadLocal pattern
		JsonWriter writer = dslJson.newWriter();

		Model instance = new Model();
		instance.string = "Hello World!";
		instance.number = 42;
		instance.integers = Arrays.asList(1, 2, 3);
		instance.decimals = new HashSet<>(Arrays.asList(BigDecimal.ONE, BigDecimal.ZERO));
		instance.uuids = new UUID[]{new UUID(1L, 2L), new UUID(3L, 4L)};
		instance.longs = new Vector<>(Arrays.asList(1L, 2L));
		instance.nested = Arrays.asList(new Model.Nested(), null);
		instance.inheritance = new Model.ParentClass();
		instance.inheritance.a = 5;
		instance.inheritance.b = 6;
		instance.person = new ImmutablePerson("first name", "last name", 35);
		instance.states = Arrays.asList(Model.State.HI, Model.State.LOW);
		instance.jsonObject = new Model.JsonObjectReference(43, "abcd");
		instance.jsonObjects = Collections.singletonList(new Model.JsonObjectReference(34, "dcba"));
		instance.map = new HashMap<>();
		instance.map.put("abc", 678);
		instance.map.put("array", new int[] { 2, 4, 8});

		dslJson.serialize(writer, instance);

		//resulting buffer with JSON
		byte[] buffer = writer.getByteBuffer();
		//end of buffer
		int size = writer.size();
		System.out.println(writer);

		//deserialization using byte[] API
		Model deser = dslJson.deserialize(Model.class, buffer, size);

		System.out.println(deser.string);
	}
 
Example #21
Source File: Example.java    From dsl-json with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static void main(String[] args) throws IOException {

		//Model converters will be loaded based on naming convention.
		//Previously it would be loaded through ServiceLoader.load,
		//which is still an option if dsljson.configuration name is specified.
		//DSL-JSON loads all services registered into META-INF/services
		//and falls back to naming based convention of package._NAME_DslJsonConfiguration if not found
		//withRuntime is enabled to support runtime analysis for stuff which is not registered by default
		//Annotation processor will run by default and generate descriptions for JSON encoding/decoding
		DslJson<Object> dslJson = new DslJson<>(Settings.withRuntime().allowArrayFormat(true).includeServiceLoader());

		Model instance = new Model();
		instance.string = "Hello World!";
		instance.number = 42;
		instance.integers = Arrays.asList(1, 2, 3);
		instance.decimals = new HashSet<>(Arrays.asList(BigDecimal.ONE, BigDecimal.ZERO));
		instance.uuids = new UUID[]{new UUID(1L, 2L), new UUID(3L, 4L)};
		instance.longs = new Vector<>(Arrays.asList(1L, 2L));
		instance.nested = Arrays.asList(new Model.Nested(), null);
		instance.inheritance = new Model.ParentClass();
		instance.inheritance.a = 5;
		instance.inheritance.b = 6;
		instance.iface = new Model.WithCustomCtor(5, 6);
		instance.person = new ImmutablePerson("first name", "last name", 35, Arrays.asList("DSL", "JSON"));
		instance.states = Arrays.asList(Model.State.HI, Model.State.LOW);
		instance.jsonObject = new Model.JsonObjectReference(43, "abcd");
		instance.jsonObjects = Collections.singletonList(new Model.JsonObjectReference(34, "dcba"));
		instance.time = LocalTime.of(12, 15);
		instance.times = Arrays.asList(null, LocalTime.of(8, 16));
		Model.Concrete concrete = new Model.Concrete();
		concrete.x = 11;
		concrete.y = 23;
		instance.abs = concrete;
		instance.absList = Arrays.<Model.Abstract>asList(concrete, null, concrete);
		instance.decimal2 = BigDecimal.TEN;
		instance.intList = new ArrayList<>(Arrays.asList(123, 456));
		instance.map = new HashMap<>();
		instance.map.put("abc", 678);
		instance.map.put("array", new int[] { 2, 4, 8});
		instance.factories = Arrays.asList(null, Model.ViaFactory.create("me", 2), Model.ViaFactory.create("you", 3), null);
		instance.builder = PersonBuilder.builder().firstName("first").lastName("last").age(42).build();
		instance.listUnoptimized = new NestedListUnoptimized(1, 2, 3);
		instance.listOptimized = new NestedListOptimized(4, 5, 6);

		ByteArrayOutputStream os = new ByteArrayOutputStream();
		//To get a pretty JSON output PrettifyOutputStream wrapper can be used
		dslJson.serialize(instance, new PrettifyOutputStream(os));

		byte[] bytes = os.toByteArray();
		System.out.println(os);

		//deserialization using Stream API
		Model deser = dslJson.deserialize(Model.class, new ByteArrayInputStream(bytes));

		System.out.println(deser.string);
	}
 
Example #22
Source File: DslJsonbProvider.java    From dsl-json with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
DslJsonb(DslJson.Settings settings) {
	dslJson = new DslJson<>(settings);
	localWriter = ThreadLocal.withInitial(dslJson::newWriter);
}
 
Example #23
Source File: GenericTest.java    From dsl-json with BSD 3-Clause "New" or "Revised" License 3 votes vote down vote up
@Test
public void willUseAnnotationProcessorVersion() throws IOException {

	DslJson<Object> customJson = new DslJson<>(Settings.basicSetup());

	byte[] bytes = "{\"VALUE\":\"ABC\"}".getBytes("UTF-8");

	Type type = new TypeDefinition<GenericFromAnnotation<String>>() {}.type;
	GenericFromAnnotation<String> result = (GenericFromAnnotation<String>)customJson.deserialize(type, bytes, bytes.length);

	Assert.assertEquals("ABC", result.value);
}