Jsonex JSONCoder is a light-weight generic object serialization / deserialization library similar to Jackson, GSON or FastJson. This library has been widely used in various eBay projects for years. It's not a replacement for other popular libraries. But it solves some specific problems which are not available or not well-supported in other alternatives.
There are plenty of options for JSON serialization/deserialization libraries, why we need another one? If you are also a fan of JSON, but hate the restrictions by JSON standards that make it so hard to be used as a configuration format, but still don't want to give up JSON to YAML (JSON is nice, why need Yet Another pretty ugly Markup Language). You can have a try of this library. This library focuses on solving following problems well:
And many more, please refer the class JSONCoderOption for more details.
Please refer the unit test class for more detailed usage patterns: JSONCoderTest
Maven Dependencies
<dependency>
<groupId>org.jsonex</groupId>
<artifactId>JSONCoder</artifactId>
<version>${jsonCoderVersion}</version>
</dependency>
You can get current version by searching maven central
Simple Serialization / Deserialization
// serialization
JSONCoder.global.encode(o)
// de-serialization
SomeClass obj = JSONCoder.global.decode(str, SomeClass.class);
Filter out fields and classes
JSONCoderOption opt = new JSONCoderOption();
// For TestBean2 and it's sub-classes, only include field: "enumField2", "testBean"
opt.addFilterFor(TestBean2.class, include("enumField2", "testBean"));("field1ForClass1", "field2ForClass1");
// For TestBean, exclude field: "publicStrField"
opt.addFilterFor(TestBean.class, exclude("publicStrField"));
// For any class, exclude field: "fieldInAnyClass"
opt.getDefaultFilter().addProperties("fieldInAnyClass");
// Exclude certain classes
opt.addSkippedClasses(SomeExcludedClass.class);
String result = JSONCoder.encode(bean, opt);
Mask out certain fields: for privacy reason, quite often when we serialize an object, we need to maskout certain fields such as emailAddress, here's example to do that:
String result = JSONCoder.encode(bean, JSONCoderOption.ofIndentFactor(2).addFilterFor(SomeBean.class, mask("field1", "field2")));
Deserialize with generic types
String str = "['str1', 'str2', 'str3']";
List<String> result = JSONCoder.global.decode(new DecodeReq<List<String>>(){}.setSource(str));
Deserialize and merge to existing object (Incremental decode)
TestBean bean = JSONCoder.global.decodeTo(jsonStr, bean);
Set custom Quote and custom indentations
JSONCoderOption opt = new JSONCoderOption();
opt.getJsonOption().setQuoteChar('`');
opt.getJsonOption().setIndentFactor(2);
String jsonStr = JSONCoder.global.encode(someObj, opt);
Register custom coder for certain classes
public class CoderBigInteger implements ICoder<BigInteger>{
public Class<BigInteger> getType() {return BigInteger.class;}
@Override public TDNode encode(BigInteger o, BeanCoderContext context, TDNode target) {
return target.setValue(o.toString());
}
@Override public BigInteger decode(TDNode jsonNode, Type type, BeanCoderContext context) {
return new BigInteger((String)jsonNode.getValue());
}
}
JSONCoderOption opt = new JSONCoderOption()
.addCoder(new CoderBigInteger());
String jsonStr = JSONCoder.global.encode(new BigInteger("1234"), opt);
Dependency Indirection with Injectable Factory
Copyright 2018-2021 eBay Inc.
Author/Developer: Jianwu Chen, Narendra Jain
Use of this source code is governed by an MIT-style license that can be found in the LICENSE file or at https://opensource.org/licenses/MIT.
Вы можете оставить комментарий после Вход в систему
Неприемлемый контент может быть отображен здесь и не будет показан на странице. Вы можете проверить и изменить его с помощью соответствующей функции редактирования.
Если вы подтверждаете, что содержание не содержит непристойной лексики/перенаправления на рекламу/насилия/вульгарной порнографии/нарушений/пиратства/ложного/незначительного или незаконного контента, связанного с национальными законами и предписаниями, вы можете нажать «Отправить» для подачи апелляции, и мы обработаем ее как можно скорее.
Опубликовать ( 0 )