簡體   English   中英

Java Web服務JSON

[英]Java Web Service JSON

我有一個REST服務,我正在嘗試使用自定義閱讀器,這是該類:

@Stateless
@Path("person")
public class PersonFacadeREST extends AbstractFacade<Person> 
implements javax.ws.rs.ext.MessageBodyReader<Person>
{
     public boolean isReadable(Class<?> type, 
                              Type genericType, 
                              Annotation[] annotations, 
                              MediaType mediaType) { 
         System.out.println("isReadable????");
        return Person.class == type; 
    } 


    public Person readFrom(Class<Person> type, 
                           Type genericType, 
                           Annotation[] annotations, 
                           MediaType mediaType, 
                           MultivaluedMap<String, String> httpHeaders, 
                           InputStream entityStream) throws IOException, WebApplicationException {
        /* This InputStream reads from the entityStream and constructs the object. */
        System.out.println("Reading data!!!!!");
        Person retObj = new Person();
        System.out.println("Read data!!!!!!!!");
        return retObj; 
    } 
REST methods snipped...

我收到一個錯誤: java.lang.IllegalArgumentException: object is not an instance of declaring class

這是應用程序類:

@javax.ws.rs.ApplicationPath("api")
public class ApplicationConfig extends Application {

    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> resources = new java.util.HashSet<Class<?>>();
        addRestResourceClasses(resources);
        return resources;
    }

    /**
     * Do not modify addRestResourceClasses() method.
     * It is automatically populated with
     * all resources defined in the project.
     * If required, comment out calling this method in getClasses().
     */
    private void addRestResourceClasses(Set<Class<?>> resources) {
        resources.add(net.mikeski.demo.service.rest.PersonFacadeREST.class);
    }

}

我這樣做是因為我有一個類,該類的Map<String, POJO>屬性沒有正確解析。 如果我刪除了MessageBodyReader的實現,則該服務將起作用。 我試圖解析的對象是:

@Entity
@Table(name = "ent_person")
public class Person implements Serializable, Comparable<Person> {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    /**
     * Comment for <code>serialVersionUID</code>
     */
    private static final long serialVersionUID = -4680156785318108346L;

    protected String firstName;

    protected String nickname;

    protected String lastName;

    @ElementCollection(fetch = FetchType.EAGER)
    protected List<String> middleNames;

    protected String idNum;

    protected char isMale;

    @Temporal(value = TemporalType.DATE)
    protected Date birthday;

    @ElementCollection(fetch=FetchType.EAGER)
    @MapKeyColumn(name = "name")
    @Column(name = "value")
    protected Map<String, PhoneNumber> phoneNumbers;

電話號碼是具有3個String屬性的POJO:

public class PhoneNumber implements Serializable {

    private static final long serialVersionUID = -423634682785318106L;

    public static transient final String HOME = "Home";

    public static final String PERSONAL_MOBILE = "Personal Mobile";

    public static final String OFFICE = "Office";

    public static final String WORK_MOBILE = "Work Mobile";

    public static final String FAX = "Fax";

    public static final String PAGER = "Pager";

    public static final String TOLL_FREE = "Toll Free";

    public static final String OTHER = "Other";

    String countryCode;

    String areaCode;

    String subscriberNubmer;

    String extension;

    public PhoneNumber() {
        super();
    }

    /**
     * @param countryCode
     * @param areaCode
     * @param subscriberNubmer
     * @param extension
     */
    public PhoneNumber(String countryCode, String areaCode, String subscriberNubmer,
            String extension) {
        super();
        this.countryCode = countryCode;
        this.areaCode = areaCode;
        this.subscriberNubmer = subscriberNubmer;
        this.extension = extension;
    }

刪除MessageBodyReader實現時發送的JSON是:

{
    "id": null,
    "firstName": "John",
    "nickname": "JJ",
    "lastName": "Smith",
    "middleNames": [
        "Stelling",
        "Deering"
    ],
    "idNum": "js3234",
    "isMale": "n",
    "birthday": 778266673889,
    "phoneNumbers": {
        "Personal Mobile": {
            "countryCode": "26",
            "areaCode": "200",
            "subscriberNubmer": "4069942",
            "extension": null
        },
        "Home": {
            "countryCode": "79",
            "areaCode": "115",
            "subscriberNubmer": "9518863",
            "extension": null
        }
    }
}

如果在Web服務加載后輸出上述JSON,這就是我得到的(請注意phoneNumber字段錯誤):

{
    "firstName":"John",
    "id":1,
    "idNum":"js3234",
    "isMale":"n",
    "lastName":"Smith",
    "middleNames":["Stelling","Deering"],
    "nickname":"JJ",
    "phoneNumbers": {
        "entry":[]
    }
 }

我以這種方式取消了工作並添加了此類,從而解決了該問題:

@Consumes("application/json")
@Provider
public class PersonReader 
 implements MessageBodyReader<Person> {
    ObjectMapper mapper;

    public PersonReader(){
        mapper = new ObjectMapper();
    }

    public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
        return type == Person.class;
    }

    public Person readFrom(Class<Person> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
        Person p = mapper.readValue(entityStream, Person.class);
        return p;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM