Cómo sustituir el valor en el archivo JSON

Pequeña ave :

Tengo un archivo JSON es decir test.json.

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

He probado el siguiente código:

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);

Resultado conseguir: -

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

Valor id: "777709" no está recibiendo la actualización a id: "12345678" pero está añadiendo al fin. Por favor, ayúdame a y dime cómo sustituir el idvalor.

flopcoder:

Puede probar esto con la biblioteca JSON sencillo ( biblioteca ). Estoy imprime de forma separada todos los objetos para la comprensión. AS se declara ID del objeto dentro de dos objetos más, por lo que en primer lugar, usted tiene que conseguir este objeto se consigue su objeto de deseo IDNew. A continuación, poner nuevo valor de ID en el campo 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();
        }

    }

}

O por razones de simplicidad se puede utilizar este

    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);

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=173700&siteId=1
Recomendado
Clasificación