0

I have an integer value, say int id whose value i get runtime by getter function. I want to replace this value of id in place of "VALUE" from .json like as follows

{ "id":"VALUE", "name": "Name updated", "description": "description Updated", "active": false }

I found following way to replace it if id is String,

String str = "myJson.json";
str.replace("\"VALUE\"", "\"id\"");

How can i use int id in above function with this format "\"id\"" ? Any other solution are welcome.

EDIT:

String str = "myJson.json";

is wrong way to get json content into String.

user3042916
  • 77
  • 2
  • 12

3 Answers3

0

You can do it with simple regex replace, e.g.:

public static void main(String[] args) {
    String value = "{\"id\":\"VALUE\",\"name\": \"Name updated\",\"description\": \"description Updated\",\"active\": false}";
    int id = 5;
    value = value.replaceAll("\"VALUE\"", String.valueOf(id));
    System.out.println(value);
}
Darshan Mehta
  • 27,835
  • 7
  • 53
  • 81
  • I do not have String. I have a Json file and int id. I need to convert the string again into the Json file. I am really new in .json kind of things. :( – user3042916 Oct 13 '16 at 13:46
  • Here is the example to replace content in files, all we need to do is to use the above example and replace String : http://stackoverflow.com/questions/3935791/find-and-replace-words-lines-in-a-filehttp://stackoverflow.com/questions/3935791/find-and-replace-words-lines-in-a-file – Darshan Mehta Oct 13 '16 at 13:51
0

Using org.json library you can assign it to JSON Object and Use the put method:

JSONObject jsonObject= new JSONObject(YOUR_STRING);
String[] names = JSONObject.getNames(jsonObject);
JSONArray jsonArray = jsonObject.toJSONArray(new JSONArray(names));

 JSONObject id=  jsonArray.getJSONObject(0).getJSONObject("id");
    person.put("VALUE", id);

regex replace may create some issue by replace someother matching string .

Karthik
  • 495
  • 5
  • 22
0

I did in following way. To replace content of Json file need to convert contents in to String. I did this with help of following function.

public static String loadJson(String jsonFileName) throws IOException {
    InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(jsonFileName);
    return IOUtils.toString(stream);
}

Then declare a String variable,

String editedJson = loadJson(TEST_SET + "myJson.json");
editedJson.replace("VALUE", "" + id);
user3042916
  • 77
  • 2
  • 12