-2

I need the following JSON format using ObjectMapper using Java.

    ObjectMapper mapper = new ObjectMapper();
    User user = new User();
    user.set_id(1);
    int id = 2;
    user.setIndex("{\"_id\":" + id + "}");
    mapper.writeValue(new File("user.json"), user);

Output: {"index":{"_id":"1"}} {"index":{"_id":"2"}}

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
AVM
  • 243
  • 3
  • 8

2 Answers2

2

Firstly,

If it is a list of users output should be

[{"index":{"_id":"1"}}, {"index":{"_id":"2"}}]

Also if you want to implement in such a way I would say use another Pojo over your base pojo so that you can easily serialize and deserialize the json as per your need. Something like this might work for you

-----------------------------------com.example.Index.java-----------------------------------

package com.example;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"index"
})
public class Index {

@JsonProperty("index")
public User index;

}
-----------------------------------com.example.Index_.java-----------------------------------

package com.example;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"_id"
})
public class User {

@JsonProperty("_id")
public String id;

}

Now to convert in the required format you can do

mapper.writeValueAsString(index); //will return a string
Parth Manaktala
  • 1,112
  • 9
  • 27
1

The output will look like the structure of the User object :

{"id":1,"index":"{\"_id\":2}"}

Not sur what you want to do. Your output format apparently not correct. What you want to display looks like a list. You would have to wrap the user object in a list to get the desired result.

Also, the "id" does not appear in your output format. Do you want to have the id value in the index directly ? You need to rethink your object or create another object to fill the output.

one track could be to change the name of json on id field by adding this :

@JsonProperty("_id")
private int id;

To have your User format try this :

public static void main(String[] args) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    User user = new User();
    user.setId(1);

    mapper.writeValue(new File("user.json"), new Index(user));
  }

  @Data
  public static class User {
    @JsonProperty("_id")
    private int    id;

    public User() {

    }
  }

  @Data
  public static class Index {
    @JsonProperty("index")
    private User user;

    public Index(User user) {
      this.user = user;
    }
  }

For me, it's definitivly a list you want Output will like this for one object :

{"index":{"_id":1}}
Yaugy
  • 11
  • 1
  • 6