English 中文(简体)
spring 3中的POJO到MultiValueMap映射/绑定/转换
原标题:POJO to MultiValueMap mapping/binding/conversion in spring 3

我有一个POJO,我需要格式化为MultiValueMap。这个MultiValueMap将在使用restTemplate类的POST方法中用作请求,并将作为contentType application/x-www-form-urlencoded传递给我的web服务。

是否有任何工具或实用程序可以执行POJO->;MultiValueMap转换对我来说?

示例pojo:

public class SampleDto implements Serializable, Idable, Comparable<SampleDto> {

    private static final long serialVersionUID = 1L;

    private Integer id;

    private Boolean active;

    private String lastName;

    private List<SurgeonClinicDto> surgeonClinics = new ArrayList<SurgeonClinicDto>();
    private List<PromptValueDto> promptValues = new ArrayList<PromptValueDto>();

    private Date lastUpdated = new Date();

    public SampleDto() {

    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Boolean getActive() {
        return active;
    }

    public void setActive(Boolean active) {
        this.active = active;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Date getLastUpdated() {
        return lastUpdated;
    }

    public void setLastUpdated(Date lastUpdated) {
        this.lastUpdated = lastUpdated;
    }

    public List<SurgeonClinicDto> getSurgeonClinics() {
        return surgeonClinics;
    }

    public void setSurgeonClinics(List<SurgeonClinicDto> surgeonClinics) {
        this.surgeonClinics = surgeonClinics;
    }

    public List<PromptValueDto> getPromptValues() {
        return promptValues;
    }

    public void setPromptValues(List<PromptValueDto> promptValues) {
        this.promptValues = promptValues;
    }

    public int compareTo(SampleDto o) {

        if (getLastName() != null && o.getLastName() != null
                && getLastName().compareTo(o.getLastName()) != 0) {
            return getLastName().compareTo(o.getLastName());
        }
        if (getActive() != null && o.getActive() != null
                && getActive().compareTo(o.getActive()) != 0) {
            return getActive().compareTo(o.getActive());
        }
        if (getLastUpdated() != null && o.getLastUpdated() != null
                && getLastUpdated().compareTo(o.getLastUpdated()) != 0) {
            return getLastUpdated().compareTo(o.getLastUpdated());
        }
        if (getId() != null && o.getId() != null
                && getId().compareTo(o.getId()) != 0) {
            return getId().compareTo(o.getId());
        }

        return 0;
    }
}

在MultiValueMap转换为contentType:application/x-www-form-urlencoded后,通过对restTemplate对象调用POST:

id=11752&active=true&lastName=Brownie&
promptValues[0].id=12&promptValues[0].miscPromptId=882&promptValues[0].value=meFirst&
promptValues[1].id=13&promptValues[1].miscPromptId=881&promptValues[1].value=youToo&
surgeonClinics[0].address1=newAddress&surgeonClinics[0].address2=newAddress2&surgeonClinics[0].city=clinic City&
surgeonClinics[0].email=email@clinic1.com&surgeonClinics[0].fax=123.456.7890&surgeonClinics[0].id=33273&
surgeonClinics[0].name=clinic name&surgeonClinics[0].phone=890-098-4567&
surgeonClinics[0].zip=34567&surgeonClinics[0].surgeryCenter1=MySurgeryCenter1&
surgeonClinics[0].surgeryCenter2=MySurgeryCenter2&
surgeonClinics[1].address1=newAddress11&surgeonClinics[1].address2=newAddress22&surgeonClinics[1].city=clinic2 City&
surgeonClinics[1].email=email@clinic2.com&surgeonClinics[1].fax=123.456.7890&surgeonClinics[1].id=33274&
surgeonClinics[1].name=clinic2 name&surgeonClinics[1].phone=890-098-4567&
surgeonClinics[1].zip=34567&
surgeonClinics[1].surgeryCenter1=MySurgeryCenter21&surgeonClinics[1].surgeryCenter2=MySurgeryCenter22
问题回答

您可以使用Jackson对象映射器:

MultiValueMap valueMap = new LinkedMultiValueMap<String, Object>();
Map<String, Object> fieldMap = objectMapper.convertValue(requestObject, new TypeReference<Map<String, Object>>() {});
valueMap.setAll(fieldMap);

你可以通过反思和/或内省来做到这一点(我永远记不起正确的名字)。这是序列化的变体,因此您可能需要查看序列化实现。

另一个选项是创建一个类似于


putlic interface ToMap
{
  Map<String, String> toMap();
}

并在有问题的类上实现它。

对于你的pojo来说,它可能看起来是这样的:


Map<String, String> toMap()
{
    int index;
    StringBuilder key = new StringBuidler();
    Map<String, String> returnValue = new HashMap<String, String&gt();

    returnValue.put("id", id);
    returnValue.put("active", active);
    returnValue.put("lastName", lastName);

    index = 0;
    for (SurgeonClinicDto surgeonClinic : surgeonClinics)
    {
        key.setLength(0);
        key.append("surgeonClinic[");
        key.append(index);
        key.append("].field1");

        returnValue.put(key.toString(), surgeonClinic[index].field1);

        key.setLength(0);
        key.append("surgeonClinic[");
        key.append(index);
        key.append("].field2");

        returnValue.put(key.toString(), surgeonClinic[index].field2);

        ... more stuff here...

    }
    return returnValue;
}

如果您希望以您在问题中指定的格式发送,那么您可能需要执行以下操作:DwB建议,但我认为如果您使用更面向对象的方法,如JSON,有很多库可以在POJO->;JSON之间转换。另一个优点是JSON句柄分别存储数字/string/booleans,因此更容易转换回POJO,而如果像您的示例中那样发送数据,则需要将所有string对象转换回它们的类型,例如,需要转换id string->;int和active字符串->;布尔值。

因此,在JSON中,它可能看起来像这样:

dto = {
    id : 11752,
    active : true,
    lastName : "Brownie",
    promptValues : [
        {id : 12, miscPromptId : 882, value : "meFirst"},
        {id : 13, miscPromptId : 881, value : "youToo"}
    ],
    surgeonClinics = [{..etc..}]
}

很明显,您可以使用XML做类似的事情,但当我想在一行中简单地发送数据时,我喜欢这个简单的解决方案。JSON库越来越好,有些库几乎可以通过反射从对象中生成JSON库。

无论如何,这只是一个建议。





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签