V. Monisha
V. Monisha

Reputation: 89

How to extract JSON data in customized format?

I have the Json data like {"no":["1","2","3"],"date":["23/05/1992","02/01/1991","01/05/1992"]} I want to split in to correct format in java.

Upvotes: 1

Views: 921

Answers (3)

Googlian
Googlian

Reputation: 6733

You can map your object through Gson library.

YourObj obj = new Gson().fromJson(jsonString, YourObj.class);

Prepare a POJO class with no and name properties.

List<String> no;
List<String> date;

Gson is an open-source Java library to serialize and deserialize Java objects to JSON.

Upvotes: 0

Vimukthi
Vimukthi

Reputation: 880

Try below code,

public class Req {
    private List<String> no;
    private List<String> date;

    public List<String> getNo() {
        return no;
    }

    public void setNo(List<String> no) {
        this.no = no;
    }

    public List<String> getDate() {
        return date;
    }

    public void setDate(List<String> date) {
        this.date = date;
    }
}

Usage

Directly using controller method

@PostMapping("/test")
public ResponseEntity<?> test(@RequestBody Req req) {
    System.out.println(req.no);
}

Create object using Gson

Gson gson = new GsonBuilder().create();
Req req = gson.fromJson(yourjson, Req.class);

Convert String date to LocalDate

String date = "02/01/1991";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/MM/yyyy");
LocalDate d = LocalDate.parse(date, formatter);

Upvotes: 0

davidxxx
davidxxx

Reputation: 131436

Two main ways :

1) Define a class to map it :

public class Foo{

   private List<String> no;
   private List<LocalDate> date;
   // setters or factory method
}

And use a Json API such as Jackson :

ObjectMapper mapper = new ObjectMapper();
Foo foo = mapper.readValue(myStringRepresentingJson, Foo.class)

You could need to use and to set a JsonDateSerializer instance to specify the date format.

2) Define a custom JSON deserializer.

It allows to control more finely and programmatically the way to map json attributes to a Java object.
With Jackson, extending the class StdDeserializer is a possibility.

Upvotes: 2

Related Questions