Monty Swanson
Monty Swanson

Reputation: 795

Java add json key value at the beginning

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"
    }
  ]
}

Upvotes: 0

Views: 817

Answers (2)

Nowhere Man
Nowhere Man

Reputation: 19565

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

Upvotes: 1

Ray Lee
Ray Lee

Reputation: 34

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

Upvotes: 2

Related Questions