JAVA json去掉外层other保留原始数据 ?


将外层的other去掉 保留原始数据

阅读 3.3k
4 个回答
✓ 已被采纳


终于解决了

把里面的json取出来,赋值给外面的json,再删除里面的json。我稍后写个demo

<script>
  const data = {
    "id": 1,
    "other": {
        "workscore-1": 10,
        "workscore-2": 20
    },
    "name": "AAA"
  }

  function fun() {
    for (let key in data.other) {
        data[key] = data.other[key];
    }
    delete data["other"]
  }

  fun()
  console.log(data);
</script>
const newDatas = datas.map(item => {
    const obj = {
        ...item,
        ...item.other
    }
    Reflect.deleteProperty(obj, 'other')
    return obj
})

在 java 中,fastjson 只有这一种处理方式。

    public static void main(String[] args) {
        String json = "{\n" +
                "    \"datas\":[\n" +
                "        {\n" +
                "            \"finalScore\":59.8,\n" +
                "            \"id\":13,\n" +
                "            \"kpiScore\":95,\n" +
                "            \"other\":{\n" +
                "                \"workScore_13\":80,\n" +
                "                \"workScore_44\":87,\n" +
                "                \"wokrScore_13\":5,\n" +
                "                \"workScore_42\":67,\n" +
                "                \"workScore_43\":67,\n" +
                "                \"wokrScore_44\":56,\n" +
                "                \"wokrScore_43\":67,\n" +
                "                \"wokrScore_42\":78\n" +
                "            },\n" +
                "            \"performanceScore\":45.5,\n" +
                "            \"userName\":\"郝巍巍\",\n" +
                "            \"workAttitude\":14.3\n" +
                "        }\n" +
                "    ]\n" +
                "}";
        JSONObject jsonObject = JSON.parseObject(json);
        JSONArray jsonArray = jsonObject.getJSONArray("datas");
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject data = jsonArray.getJSONObject(i);
            String other = data.getJSONObject("other").toString(SerializerFeature.PrettyFormat);
            other = other.substring(other.indexOf('\n') + 1);
            other = other.substring(0, other.lastIndexOf('\n'));
            System.out.println(other.replace("\t", ""));

            // 或者是
            String other1 = data.getJSONObject("other").toString(SerializerFeature.PrettyFormat);
            System.out.println(other1.substring(1, other1.length() - 1).replace("\t", ""));
        }
    }

jackson 补充,能够直接获取

        try {
            JsonNode root = new ObjectMapper().readTree(json);
            JsonNode inputs = root.path("datas").path(0);
            System.out.println(inputs.path("other").asText());
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题