简体   繁体   English

解析其余API的json响应并删除某些jsonObjects-JAVA

[英]Parse json response of rest API and delete certain jsonObjects - JAVA

I have a json file as below which I am getting as a response from rest API: 我有一个下面的json文件,我从rest API得到响应:

{
  "label": " MARA LEYZIN",
  "ClassCode": "PROFESSIONAL",
  "actvFlg": "A",
  "name": "MARA LEYZIN",
  "Typ": {
    "label": "C_TYP_LU",
    "TypCode": "PROFESSIONAL  "
  },
  "Address": {
    "link": [],
    "firstRecord": 1,
    "pageSize": 10,
    "searchToken": "multi",
    "item": [
      {
        "label": "Address",
        "addrTypFk": {
          "label": "C_ADDRESS_TYPE_LU",
          "addrTypCd": "INDUSTRY",
          "addrTypDesc": "Industry"
        }
}
]
}

I am trying to parse this in Java and to remove some unwanted json objects. 我正在尝试用Java解析它并删除一些不需要的json对象。 Like I want the following string to be replaced by blank: 就像我希望将以下字符串替换为空白:

"link": [],
    "firstRecord": 1,
    "pageSize": 10,
    "searchToken": "multi",
    "item":

To achieve this I am trying the following approach: 为此,我正在尝试以下方法:

String jsonStr = new String(Files.readAllBytes(Paths.get(inputFile)));
System.out.println(jsonStr);
jsonStr.replaceAll("link", "");

But it is not replacing the required string with blanks. 但这不是用空格替换所需的字符串。 Please help me in this. 请帮助我。

string object is immutable , so basically if do you want to replace something 字符串对象是不可变的,因此基本上,如果您要替换某些东西
System.out.println(jsonStr.replaceAll("link", "")); this will print the replaced string but it will not affect the original string, however if you do this 这将打印替换的字符串,但不会影响原始字符串,但是,如果执行此操作

jsonStr=jsonStr.replaceAll("link", "");

System.out.println(jsonStr); this will print the replaced string 这将打印替换的字符串

First of all: Your JSON is not validate. 首先:您的JSON未通过验证。 You're missing a closing curly bracket at the end of it. 您在结尾处缺少右花括号。

{
"label": " MARA LEYZIN",
"ClassCode": "PROFESSIONAL",
"actvFlg": "A",
"name": "MARA LEYZIN",
"Typ": {
    "label": "C_TYP_LU",
    "TypCode": "PROFESSIONAL  "
},
"Address": {
    "link": [],
    "firstRecord": 1,
    "pageSize": 10,
    "searchToken": "multi",
    "item": [{
        "label": "Address",
        "addrTypFk": {
            "label": "C_ADDRESS_TYPE_LU",
            "addrTypCd": "INDUSTRY",
            "addrTypDesc": "Industry"
        }
    }]
}

} }

Second of all you should just change order of your commands to this: 其次,您应该将命令顺序更改为:

jsonStr.replaceAll("link", "");
System.out.println(jsonStr);

Important addition : And I would suggest you to use org.json library or even better JACKSON to parse JSON files. 重要补充 :我建议您使用org.json库甚至更好的JACKSON来解析JSON文件。

Here's tutorial how to use jackson and it's my warmest suggestion. 这是如何使用杰克逊的教程 ,这是我最热烈的建议。 You will save a lot of time and you can do whatever you like. 您将节省大量时间,并且您可以做任何喜欢的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM