0

how do I append value to an existing json array ?

I have existing json array with below values

{
  "test": [
    1,
    2,
    3,
    4
  ]
} 

I wanted to add "0" in to the json array so that the new json array would look like

{
  "test": [
    0,  
    1,
    2,
    3,
    4
  ]
} 
testerBDD
  • 255
  • 3
  • 18

1 Answers1

1

Using Java and the Jackson library, you can deserialize the (json) String to a Java object, add the entry, and then serialize the modified object (print it to Json format).

In example, with this code

package json;
import java.util.Collections;
import java.util.List;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class UseJson {
  public static void main(String[] args) throws Exception {
    ObjectMapper om = new ObjectMapper();
    String json = "{\r\n" + 
    "  \"test\": [\r\n" + 
    "    1,\r\n" + 
    "    2,\r\n" + 
    "    3,\r\n" + 
    "    4\r\n" + 
    "  ]\r\n" + 
    "} ";
    System.out.println("json="+json);
    Wrap val = om.readValue( json, Wrap.class);
    System.out.println("read val="+val);
    val.test.add(0);
    Collections.sort(val.test);
    System.out.println("val="+val);
    om.enable(SerializationFeature.INDENT_OUTPUT);
    String json2 = om.writeValueAsString(val);
    System.out.println("json2="+json2);
  }
}

class Wrap {
  public List<Integer> test;
  @Override
  public String toString() {
    return "Wrap[test=" + test + "]";
  }
}

you get..

json={
  "test": [
    1,
    2,
    3,
    4
  ]
} 
read val=Wrap[test=[1, 2, 3, 4]]
val=Wrap[test=[0, 1, 2, 3, 4]]
json2={
  "test" : [ 0, 1, 2, 3, 4 ]
}

(to be compiled in a Maven project including jackson-core and jackson-databind)

Daniele
  • 2,672
  • 1
  • 14
  • 20