【问题标题】:Remove outermost node from the JSON payload从 JSON 有效负载中删除最外层节点
【发布时间】:2021-12-08 00:36:23
【问题描述】:

我需要从下面的 JSON paylaod 中删除最外层的元素(ns0:TableData)。

{
    "ns0:TableData": {
        "descr": 111,
        "note": 11,
        "kpar": 1111,
        "karr": 111,
        "xmlns:ns0": "urn:it:alia:inaz",
        "codice": 1,
        "dend": 1111,
        "anz_app_a": 1,
        "dini": 11
    }
}

我正在使用下面的代码将传入的 XML 转换为 JSON

String inputData = IOUtils.toString(inputstream);
System.out.println(inputData);
JSONObject xmlJSONObj = XML.toJSONObject(inputData);
String jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR);
System.out.println(jsonPrettyPrintString);

【问题讨论】:

  • 一个粗略但简单的解决方案是使用老式的字符串操作,即 String.replace() 删除 ""ns0:TableData": {" 和最后一个 "}"。

标签: java json xml org.json


【解决方案1】:

试试这个例子

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.Data;
import lombok.ToString;

public class Main {
    @Data
    @ToString
    private static class All {
        @JsonProperty("descr")
        int descr;
        int note;
        int kpar;
        int karr;
        @JsonProperty("xmlns:ns0")
        String xmlnsNs0;
        int codice;
        int dend;
        @JsonProperty("anz_app_a")
        int anzAppA;
        int dini;
    }

    public static void main(String[] args) throws JsonMappingException, JsonProcessingException {
        String json = "{\n" //
                + "    \"ns0:TableData\": {\n" //
                + "        \"descr\": 111,\n" //
                + "        \"note\": 11,\n" //
                + "        \"kpar\": 1111,\n" //
                + "        \"karr\": 111,\n" //
                + "        \"xmlns:ns0\": \"urn:it:alia:inaz\",\n" //
                + "        \"codice\": 1,\n" //
                + "        \"dend\": 1111,\n" //
                + "        \"anz_app_a\": 1,\n" //
                + "        \"dini\": 11\n" //
                + "    }\n" //
                + "}\n" 
                + "";
        ObjectMapper obj = new ObjectMapper();
        JsonNode jstree = obj.readTree(json);
        JsonNode data = jstree.get("ns0:TableData");
        All a = obj.readValue(data.toString(), All.class);
        System.out.println(a);
    }
}

【讨论】:

    【解决方案2】:

    在 XPath 3.1 中,使用 json-doc('input.json')?*

    【讨论】:

    • 感谢您的回复,但您能帮我看看如何在上面的代码中使用它
    • 好吧,老实说,我不会从这里开始。像 XML.toJSONObject() 这样的标准库转换永远不会产生您真正想要的 JSON。我不会使用 XSLT3 对现成转换器的输出进行后处理(您可以按照建议进行),而是进行自定义 XML 到 JSON 的转换。但是在 StackOverflow 上,我们应该回答人们的问题,而不是解决他们的问题,我在这里偏离了你的问题。
    猜你喜欢
    • 1970-01-01
    • 2021-09-27
    • 2015-10-14
    • 2023-02-23
    • 1970-01-01
    • 1970-01-01
    • 2019-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多