【问题标题】:How to replace value in json file如何替换json文件中的值
【发布时间】:2018-11-21 09:57:17
【问题描述】:

我有一个 JSON 文件,即test.json

{
  "Added": {
    "type": "K",
    "newmem": {
      "IDNew": {
        "id": "777709",
        "type": "LOP"
      },
      "birthDate": "2000-12-09"
    },
    "code": "",
    "newest": {
      "curlNew": "",
      "addedForNew": ""
    }
  }
}

我尝试了以下代码:

File file = new File("test.json");
JSONParser parser = new JSONParser();

JSONObject data =  (JSONObject) parser.parse(
   new FileReader(file.getAbsolutePath()
));//path to the JSON file.
System.out.println(data.toString());

JSONObject jObject  = new JSONObject();
jObject.put("id","12345678");
System.out.println(jObject);

结果获取:-

{
  "Added": {
    "type": "K",
    "newmem": {
      "IDNew": {
        "id": "777709",
        "type": "LOP"
      },
      "birthDate": "2000-12-09"
    },
    "code": "",
    "newest": {
      "curlNew": "",
      "addedForNew": ""
    }
  }
}{
"id":"12345678"
}

id: "777709" 没有更新到 id:"12345678" 但它终于添加了。请帮助我并告诉我如何替换 id 值。

【问题讨论】:

  • 您需要将该json对象再次写入文件。
  • 您没有修改原始对象。您刚刚创建了一个新的空的 (jOjbect),向其中添加了一个元素并打印。您需要改为修改data
  • @FedericoklezCulloca 你能帮忙实现一下吗?我对 java 很陌生,也没有在 Net 上得到任何好的参考。

标签: java json


【解决方案1】:

你可以用简单的 json library(library) 试试这个。我单独打印所有对象以供理解。当您在另外两个对象中声明 Id 对象时,首先您必须获取此对象,然后获取您想要的对象 IDNew。然后将新的 id 值放入 id 字段中。

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class Main {

    private static final String filePath = "E:\\project-test\\scloud\\test\\src\\main\\resources\\test";

    public static void main(String[] args) {

        try {
            // read the json file
            FileReader reader = new FileReader(filePath);

            JSONParser jsonParser = new JSONParser();
            JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);

            System.out.println(jsonObject);


            JSONObject addedObj = (JSONObject) jsonObject.get("Added");
            System.out.println("Added is: " + addedObj);

            JSONObject newmemObject =(JSONObject) addedObj.get("newmem");
            System.out.println("newmemObject is: " + newmemObject);

            JSONObject idNewObj =(JSONObject) newmemObject.get("IDNew");
            System.out.println("IdNewObj is: " + idNewObj);

            long id =Long.valueOf((String) idNewObj.get("id"));
            System.out.println(id);


            idNewObj.put("id",809809809);

            System.out.println(jsonObject);

        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (ParseException ex) {
            ex.printStackTrace();
        } catch (NullPointerException ex) {
            ex.printStackTrace();
        }

    }

}

或者为简单起见,您可以使用它

    FileReader reader = new FileReader(filePath);
    JSONParser jsonParser = new JSONParser();
    JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
    System.out.println(jsonObject);

    JSONObject idObj = (
       (JSONObject) (
             (JSONObject) (
                (JSONObject)
                   jsonObject.get("Added")
             ).get("newmem")
       ).get("IDNew")
    );

    idObj.put("id", 98009809);
    System.out.println("After ID value updated : "+jsonObject);

【讨论】:

  • 谢谢!它有效:) 我可以在控制台中看到打印的 json 值。如何在同一个 test.json 文件中写入相同的值?
  • 试试这个: FileOutputStream outputStream = new FileOutputStream("test"); byte[] strToBytes = jsonObject.toString().getBytes(); outputStream.write(strToBytes);
【解决方案2】:

您可以使用 simple-json java lib 更新 JSONObject 中的嵌套元素,如下所示:

JSONObject added = (JSONObject) data.get("Added");
JSONObject newmem = (JSONObject) added.get("newmem");
JSONObject idNew = (JSONObject) newmem.get("IDNew");
idNew.put("id","12345678");
System.out.println(data);

【讨论】:

  • 我尝试了同样的方法,最后添加了一个新值
  • get("").put("","") ; get 方法不会为我返回任何 put 方法。
  • 已导入 import org.json.JSONException;导入 org.json.simple.JSONObject;导入 org.json.simple.parser.JSONParser;导入 org.json.simple.parser.ParseException;
  • 你用try catch包围它了吗?
  • @KaranMer 是的,我用 Try and Catch 发表了评论
【解决方案3】:

使用不同库的另一种解决方案json-path

import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Option;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.io.File;
import java.io.IOException;

import static org.assertj.core.api.Assertions.assertThat;

    @Test
    public void exampleToReplaceSingleElement_jsonTakenFromFile() throws IOException {
        String expectedId = "12345678";
        String expectedJson = "{\n" +
                "  \"Added\": {\n" +
                "    \"type\": \"K\",\n" +
                "    \"newmem\": {\n" +
                "      \"IDNew\": {\n" +
                "        \"id\": \"12345678\",\n" +
                "        \"type\": \"LOP\"\n" +
                "      },\n" +
                "      \"birthDate\": \"2000-12-09\"\n" +
                "    },\n" +
                "    \"code\": \"\",\n" +
                "    \"newest\": {\n" +
                "      \"curlNew\": \"\",\n" +
                "      \"addedForNew\": \"\"\n" +
                "    }\n" +
                "  }\n" +
                "}";

        Configuration configuration = Configuration
                .builder()
                .options(Option.SUPPRESS_EXCEPTIONS)
                .build();
        File json = new File("src/test/resources/test.json");
        System.out.println(json.getAbsolutePath());
        DocumentContext parsed = JsonPath.using(configuration).parse(json);

        parsed.set("$.Added.newmem.IDNew.id", expectedId);
        String actual = parsed.jsonString();

        log.info("After ID value updated: {}", actual);
        assertThat(actual).isEqualToIgnoringWhitespace(expectedJson);
    }

也可以通过获取 test exampleToReplaceSingleElement()test exampleToReplaceSingleElement_jsonTakenFromFile() 访问示例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多