-1

I have a class in Java that I want to convert to JSON. The server which accepts this input expects a single-element JSON array, containing a key-value map

For instance, if you have a class as shown:

public class Input {

    private String id1;
    private int id2;
    private String s1;
    private String s2;
    private String s3;
    ...
}

// Code which converts above class to JSON string:
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
Input input = new Input(id1, id2, s1, s2, s3);
System.out.println(objectMapper.writeValueAsString(input));

// Actual Output:
{"id1":"...","id2":...,"s1":"c...","s2":"...","s3":"..."}

// Expected Output:
[{"id1":"...","id2":...,"s1":"c...","s2":"...","s3":"..."}]

Any idea how to get the 'Expected Output'?

Marsroverr
  • 556
  • 1
  • 6
  • 23
Jared
  • 73
  • 6

3 Answers3

0

You can put your JSONObject into JSONArray like shown below.

JSONObject obj = new JSONObject();
obj.put("firstName", firstName);
obj.put("lastName", lastName);

JSONArray array = new JSONArray();
array.put(obj)
Himanshu Singh
  • 2,117
  • 1
  • 5
  • 15
0

Two ways to do that (given the poor question specs)

The ugly

System.out.println("[" + objectMapper.writeValueAsString(input) + "]");

The good

Input[] input = new Input[] { new Input(id1, id2, s1, s2, s3) };
System.out.println(objectMapper.writeValueAsString(input));
Vincent Mimoun-Prat
  • 28,208
  • 16
  • 81
  • 124
0

One way to do this is:

System.out.println(objectMapper.writeValueAsString(new Object[] { input }));
Jared
  • 73
  • 6