0

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

Vombat
  • 1,156
  • 1
  • 15
  • 27

5 Answers5

2

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
 }
dev8080
  • 3,950
  • 1
  • 12
  • 18
0

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

class Subject{
  List<String> categories;

 // getters and setters
}
rackdevelop247
  • 86
  • 1
  • 10
  • check this answer ...https://stackoverflow.com/questions/24864489/could-not-read-json-can-not-deserialize-instance-of-hello-country-out-of-star – rackdevelop247 Jun 27 '17 at 09:50
0

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;
   }
 }
Zuko
  • 2,764
  • 30
  • 30
0

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);

0

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.

ledniov
  • 2,302
  • 3
  • 21
  • 27