采用Elasticsearch Client SDK 实现 JSON 字符串 和 Java对象的相互转换
public static void main(String[] args) throws IOException {
//Object to JSON String
Map phases = new HashMap<>();
Map hotActions = new HashMap<>();
hotActions.put(RolloverAction.NAME, new RolloverAction(
new ByteSizevalue(50, ByteSizeUnit.GB), null, null));
phases.put("hot", new Phase("hot", Timevalue.ZERO, hotActions));
Map deleteActions =
Collections.singletonMap(DeleteAction.NAME, new DeleteAction());
phases.put("delete", new Phase("delete",
new Timevalue(90, TimeUnit.DAYS), deleteActions));
LifecyclePolicy policy = new LifecyclePolicy("my_policy",
phases);
PutLifecyclePolicyRequest request =
new PutLifecyclePolicyRequest(policy);
XContentBuilder xContentBuilder = JsonXContent.contentBuilder();
request.toXContent(xContentBuilder, ToXContent.EMPTY_PARAMS);
String json = Strings.toString(request, true, true);
System.out.println(json);
//JSON String to Object
String json2 = "{n"
+ " "phases" : {n"
+ " "hot" : {n"
+ " "min_age" : "0ms",n"
+ " "actions" : {n"
+ " "rollover" : {n"
+ " "max_size" : "50gb"n"
+ " }n"
+ " }n"
+ " },n"
+ " "delete" : {n"
+ " "min_age" : "90d",n"
+ " "actions" : {n"
+ " "delete" : { }n"
+ " }n"
+ " }n"
+ " }n"
+ " }";
//根据解析的对象,设置不同的NamedXContentRegistry
final XContentParser parser = XContentType.JSON.xContent().createParser(new NamedXContentRegistry(new IndexLifecycleNamedXContentProvider().getNamedXContentParsers()),
new DeprecationHandler() {
@Override
public void usedDeprecatedName(String usedName, String modernName) {
}
@Override
public void usedDeprecatedField(String usedName, String replacedWith) {
}
}, json2);
final LifecyclePolicy test_policy_name = LifecyclePolicy.parse(parser, "test_policy_name");
test_policy_name.toXContent(xContentBuilder, ToXContent.EMPTY_PARAMS);
System.out.println(Strings.toString(test_policy_name, true, true));
}



