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
  ]
} 
2
  • 2
    What library (if any) are you using? And have you tried anything thus far? Commented Feb 11, 2019 at 16:22
  • Do you really mean Java or JavaScript (I assume you know the difference :) )? Commented Feb 11, 2019 at 16:32

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.