简体   繁体   English

Java Web服务JSON

[英]Java Web Service JSON

I have a REST service that I am trying to use a custom reader for, and this is the class: 我有一个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...

I get an error: java.lang.IllegalArgumentException: object is not an instance of declaring class 我收到一个错误: java.lang.IllegalArgumentException: object is not an instance of declaring class

Here is the application 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);
    }

}

I'm doing this because I have a class that has a property of Map<String, POJO> that is not being parsed correctly. 我这样做是因为我有一个类,该类的Map<String, POJO>属性没有正确解析。 If I remove the implementation of the MessageBodyReader the service works. 如果我删除了MessageBodyReader的实现,则该服务将起作用。 The object I am trying to parse is: 我试图解析的对象是:

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

The phone number is a POJO with 3 String properties: 电话号码是具有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;
    }

The JSON I send when the MessageBodyReader implementation is removed is: 删除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
        }
    }
}

If I output the above JSON after the web service loads it, here is what I get (note the phoneNumber field is wrong): 如果在Web服务加载后输出上述JSON,这就是我得到的(请注意phoneNumber字段错误):

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

I scrapped doing things this way and added this class, which resolved the problem: 我以这种方式取消了工作并添加了此类,从而解决了该问题:

@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