Jersey: Json array with 1 element is serialized as object

前端 未结 8 2120
眼角桃花
眼角桃花 2021-01-03 19:20

I\'m creating a REST server with Jersey/Java and I found a strange behavior.

I have a method on the server that returns an array of objects as Json

@         


        
相关标签:
8条回答
  • 2021-01-03 20:05

    I'm using cxf, here is my applicationContext.xml to force array in JSON:

    <jaxrs:server id="myService" serviceName="MyService"
    address="/mysvc">
    <jaxrs:serviceBeans>
        <ref bean="myServiceImpl"/>
    </jaxrs:serviceBeans>
    <jaxrs:providers>
        <bean class="org.apache.cxf.jaxrs.provider.json.JSONProvider">
       <property name="dropRootElement" value="true" />
       <property name="supportUnwrapped" value="true" />
       <property name="namespaceMap">
          <map>
            <entry key="http://example.com/myservice" value=""/>
          </map>
       </property>
       <property name="arrayKeys">
          <list>
        <value>fileInfo</value>
          </list>
       </property>                          
        </bean>
    </jaxrs:providers>
    </jaxrs:server>
    
    0 讨论(0)
  • 2021-01-03 20:06

    I've struggled quite a bit and found this simple solution

    In your pom.xml:

    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-jaxrs</artifactId>
        <version>1.9.13</version>
    </dependency>
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-xc</artifactId>
        <version>1.9.13</version>
    </dependency>
    

    In your web.xml:

    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>com.other-packages;org.codehaus.jackson.jaxrs</param-value>
    </init-param>
    
    0 讨论(0)
提交回复
热议问题