为什么 tWriteJSONField 为空值创建一个数组?

Why does tWriteJSONField create an array for null values?

我已在 OracleXE 的 HR 示例数据库中将国家/地区加入位置。

然后我使用 tMap 生成嵌套的 JSON 文档。

它有效,但由于某些原因,Location 中的空值在控制台的最终输出中作为数组出现(也尝试过 MongoDB)。

因为 tWriteJSONField 生成一个 xml,然后使用 json-lib 将其转换为 JSON。您的 null 值将被转换为空 xml 节点 <STATE_PROVINCE/>,而 json-lib 没有此节点的上下文,将假定它是没有子节点的父节点,而不是空的文本(此时空概念已经很远了)。

这是简而言之:

package test.json;

public class JSONTest {

    public static void main(String[] args) {
        net.sf.json.xml.XMLSerializer s = new net.sf.json.xml.XMLSerializer();
        s.clearNamespaces();
        s.setSkipNamespaces(true);
        s.setForceTopLevelObject(true);
        net.sf.json.JSON json = s.read("<?xml version=\"1.0\" encoding=\"ISO-8859-15\"?>" +
                "<org>" +
                "<STATE_PROVINCE/>" +
                "</org>"
        );
        System.out.println(json.toString());
    }

}

结果:

{"org":{"STATE_PROVINCE":[]}}

一个肮脏的解决方案是在您的 tWriteJSONField 中使用属性而不是节点,但它会在您的属性前加上@。所以在这个组件之后你放了一个 tReplace,搜索 "\"@",用 "\"" 替换,取消选中整个单词,选中全局表达式。如果为空,您的最终 JSON 将没有 属性。

感谢https://www.talendforge.org/forum/viewtopic.php?id=27791

在你的 tWriteJsonField 之后插入一个 tJavaRow 和下面的代码:

output_row.output = input_row.output.replaceAll(",?\"[a-zA-Z_0-9]*\":\[\]", "");

我相信优雅(和简短)的解决方案如下。

Talend docs 说明:

When configuring a JSON tree, the default type of an element is string. If an element is not of type string, you need to add an attribute for the element to set its type.

因此,对于接收空值的对象,您应该添加一个名为 class 的属性并将其静态值设置为 object.

Pic: JSON Tree Configuration

瞧瞧!

PIC: "Complemento":null