0

I have a json string jsonstring that looks like this

{
  "Users": [
    {
      "Name": "Appli",
      "ID": "519"
    },
    {
      "Name": "Dash",
      "ID": "602"
    }
  ]
}

How do I add a key value pair in front of Users like so:

{
  "Department":"Accounting", 
  "Users": [
    {
      "Name": "Appli",
      "ID": "519"
    },
    {
      "Name": "Dash",
      "ID": "602"
    }
  ]
}
Monty Swanson
  • 695
  • 16
  • 41
  • 3
    according to spec the sequence should not matter. "An object is an unordered set of name/value pairs." . https://stackoverflow.com/questions/16870416/does-the-sequence-of-the-values-matter-in-a-json-object – Marc Stroebel Jun 24 '20 at 06:31
  • 2
    Use a JSON library, then parse the JSON text, add the extra key/value pair, and regenerate JSON text. Exactly how to do it depends entirely on which JSON library you choose. – Andreas Jun 24 '20 at 06:33

2 Answers2

2

Hi you can try format String to JSONObject , then use JSONObject set key value

try {
     JSONObject jsonObject = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
}catch (JSONException err){
     Log.d("Error", err.toString());
}
Ray Lee
  • 34
  • 4
1

To address this specific case you may identify the pattern and use String.replaceAll method like this:

String usersWithDepartment = jsonstring.replaceAll(
    "(\"Users\":\\s*\\[)", // find a pattern for "Users" element
    "\"Department\": \"Accounting\",\n  $1" // add a prefix and keep the group $1 as is
);
System.out.println(usersWithDepartment);

This is a quick fix and of course more appropriate approach is to use some JSON processing library as mentioned in the comments.

update

If several occurrences of \"Users\" array are possible in the input string and you need to add the prefix only to the first occurrence, the regexp should be changed to:

String usersWithDepartment = jsonstring.replaceAll(
    "(?s)(\"Users\":\\s*\\[.*$)", // grab entire string, enable multiline selection
    "\"Department\": \"Accounting\",\n  $1" // add prefix
);
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42