简体   繁体   English

骡子 4:如何将 Java 自定义 Object 转换为 JSON

[英]Mule 4: How to transform a Java Custom Object to JSON

I have a Custom Java Object class as below:我有一个自定义 Java Object class 如下:

package com.me;

public class Person {
    
    String firstName;
    String lastName;
    
    public String toString(){
        return "{firstName=" + this.firstName + ",lastName=" + this.lastName + "}";
    }

}

I would like to transform a JSON payload to this Object, then transform it back to JSON.我想将 JSON 有效负载转换为此 Object,然后将其转换回 JSON。 To do this, I use Dataweave and the below Transform Message processor:为此,我使用 Dataweave 和下面的转换消息处理器:

%dw 2.0
output application/java 
---
{
  "firstName": "Mickey",
  "lastName": "Mouse",
} as Object {class : "com.me.Person"}

This returns the Object with first and last name updated.这将返回 Object 并更新了名字和姓氏。 Afterwards, I try to transform it back to JSON with the below script:之后,我尝试使用以下脚本将其转换回 JSON:

%dw 2.0
output application/json
---
payload

However, this returns an empty JSON Object但是,这会返回一个空的 JSON Object

{}

How can I update my Java class in order to get a JSON payload similar to:如何更新我的 Java class 以获得类似于以下内容的 JSON 有效负载:

{
      "firstName": "Mickey",
      "lastName": "Mouse"
}

You need to add at least the getter methods for the fields you want in your JSON.您至少需要在 JSON 中为您想要的字段添加 getter 方法。

public String getFirstName() {
    return firstName;
}

public String getLastName() {
    return lastName;
}

After adding these methods, your object will be converted to JSON as you are expecting.添加这些方法后,您的 object 将按照您的预期转换为 JSON。

If you can not change your class, you will need to construct JSON in your transform message after you have created the Java Object. If you can not change your class, you will need to construct JSON in your transform message after you have created the Java Object. Like this像这样

%dw 2.0
output application/json
---
{
  "firstName": payload.firstName,
  "lastName": payload.lastName,
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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