简体   繁体   中英

List becomes String when Marshalling object to json

I'm getting a pretty strange error when marshalling my object to json. My object is annotated like this.

My class:

@XmlRootElement(name = "myobject")
public class MyObject {

private List<String> contactPersonsForMyObject;

@javax.xml.bind.annotation.XmlElement()
public List<String> getContactPersonsForMyObject() {
    return contactPersonsForMyObject;
}

public void setContactPersonsForMyObject(List<String> contactPersonsForMyObject) {
    this.contactPersonsForMyObject = contactPersonsForMyObject;
   } 
}

Everything works fine except for that if the List contactPersonsForMyObject contains only one value it get's marshalled to a string which ofcourse creates problems since the application consuming this expects a list.

The marshalled object:

[
        {
            "myobject": {
                "somethingcool": "amazing",
                "contactPersonsForMyObject": [
                    "test.test@gmail.com",
                    "test@test.se"
                ],
                "myObjectId": "c85e48730501bfae41e67714c6131b7d"
            }
        },
        {
            "myobject": {
                "somethingcool": "cool",
                "contactPersonsForMyObject":"test@test2.se",                
                "myObjectId": "c85e48730501bfae41e67714cqwerty"
            }
        }
    ]

Why does this happen and how do I force it to create a list with one value?

Try using Jackson to handle processing your objects into JSON, it solved the same array problem for me in the past. If you are using RESTEasy (version 1.2 GA) with Maven, this link should help you get things setup to use Jackson to serialize objects to JSON.

This article also has some useful information for integrating Jackson with RESTEasy. Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM