采用Elasticsearch Client SDK 实现 JSON 字符串 和 Java对象的相互转换
KXSW

public static void main(String[] args) throws IOException {
        //Object to JSON String
        Map<String, Phase> phases = new HashMap<>();
        Map<String, LifecycleAction> 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<String, LifecycleAction> 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));
    }
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐