Vombat
Vombat

Reputation: 1166

Json object to pojo conversion

I have a json like this:

 "subject": {
 "category": [
  {
   "name": "name1"
  },
  {
   "name": "name2"
  },
  {
   "name": "name3"
  },
  {
   "name": "name4"
  }
 ]
}

So it is an object containing a name array. What could be an equivalent Pojo for this?

Should I create a Subject object which has a string list called category?

I tried this:

public class Subject {


@JsonProperty(value = "category")
private List<String> name;

//getter setter ...
}

But I get nested exception: com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token

Upvotes: 0

Views: 4934

Answers (5)

ledniov
ledniov

Reputation: 2382

In addition to dev8080 answer I would suggest using jsonschema2pojo service.

If you paste there your source JSON and select Source type: JSON you will have the following output:

---------------com.example.Subject.java---------------

package com.example;

import java.util.ArrayList;
import java.util.List;
import javax.validation.Valid;

public class Subject {

    @Valid
    private List<Category> category = new ArrayList<Category>();

    public List<Category> getCategory() {
        return category;
    }

    public void setCategory(List<Category> category) {
        this.category = category;
    }

}

---------------com.example.Category.java---------------

package com.example;

public class Category {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

And you can easily tweak it using options or adopt some parts by hand.

Upvotes: 0

Zuko
Zuko

Reputation: 2914

Why don't you just use Gson. Its pretty solid and well tested.

 Subject subject = new Gson().fromJson(jsonObject.toString(), Subject.class);

You can also try this if Gson isn't an option here

 public class Subject{
   private List<Category> category;
   //setter/getter(s)        

   private static class Category{
      String name;
   }
 }

Upvotes: 0

Muhammad Shahid
Muhammad Shahid

Reputation: 1

In this json file you have Subject object containing one Array of objects "category" if you need values from that Subject object you should extract like this console.log(Subject.category[0].name);

Upvotes: 0

dev8080
dev8080

Reputation: 4030

Every object should ideally be a class and every array a collection in Java. It should be:

public class Subject {
    private List<Category> category;
    //getters and setters
 }


 class Category{
    String name;
   //getters and setters
 }

Upvotes: 2

rackdevelop247
rackdevelop247

Reputation: 86

yes you are right ..you can implement POJO like you mentioned

class Subject{
  List<String> categories;

 // getters and setters
}

Upvotes: 0

Related Questions