请帮我找出问题所在。我用 groovy 编程(你可以使用 java 示例,它看起来像那里)。Json 来到输入,其中不知道有多少字段。可能有 5 个字段,可能有 10 个,也可能有 50 个。我的任务是处理这个 json 并使用以下方法返回数据:
// Names of dataset columns
def names = ["a", "b", "c"];
// types of return values in each column (for any field (column) json is always String)
def types = ["String", "String", "String"];
// formation of the dataset header
reader.outputLinesSetHeaders (names, types);
// Passing the data itself from json
reader.outputLines ([it.a, it.b, it.c])
// Close the dataset
reader.outputLinesEnd ();
如果我知道传入的 json,那么我会提前设置所需的字段名称,“String”的数量,并通过引用特定的 json 字段返回它们的值。下面的示例显示了 3 个 json 字段:auto、home、job。因此,每个字段的 3 倍“字符串”并引用特定字段以返回 it.auto、it.home、it.job 的值。但是,如果我不知道传入的 json,我该怎么做呢?
import groovy.json.JsonSlurper
import ru.itrpro.xm.plugins.groovy.ResultSetReader;
class XM_PARSE_XLS {
def execute(ResultSetReader reader, String pfile) {
def jsonSlurper = new JsonSlurper()
def list = jsonSlurper.parseText(pfile)
//The names of the columns of the dataset (now set statically to show an example; but in my case I don't know json and can't write it this way in advance)
def names = ["AUTO", "HOME", "JOB"];
//return types in each column (for any json, only "String" types)
def types = ["String", "String", "String"];
//формирование заголовка датасета
reader.outputLinesSetHeaders(names,types);
list.each {
//pass the values as a dataset from json (now set statically to show an example; but in my case I don't know json and can't write it this way in advance)
reader.outputLines([it?.AUTO, it?.HOME, it?.JOB]);
}
//closing dataset
reader.outputLinesEnd();
return null;
}
static void main(String... args) {
String pfile = """
[{"AUTO":"bmw",
"HOME":"vest",
"JOB":"bbds"},
{"AUTO":"audi",
"HOME":"dest",
"JOB":"aads"},
{"AUTO":"opel",
"HOME":"lest",
"JOB":"ffds"}]
"""
def SSC = new XM_PARSE_XLS()
def res = SSC.execute(new ResultSetReader(), pfile)
}
}
也许值得将传入 json 的所有字段名称收集到一个列表中,并指定一个与字段编号相同的“字符串”列表(任何传入 json 的所有字段都只有“字符串”)?但是如何做到这一点,然后我应该如何传递字段值(它。***)?