java - 有没有办法使用 Jackson 和/或其关联库之一(csv、json 等)将字符串转换为 Java 类型

标签 java jackson type-conversion jackson-dataformat-csv

是否有一种机制可以应用一组标准检查来检测字符串,然后使用 Jackson 的标准文本相关库之一(csv、json,甚至 jackson-core)将字符串转换为检测到的类型?我可以想象将它与与该值关联的标签(例如 CSV header )一起使用来执行类似以下的操作:

JavaTypeAndValue typeAndValue = StringToJavaType.fromValue(Object x, String label);  
typeAndValue.type() // FQN of Java type, maybe
typeAndValue.label() // where label might be a column header value, for example
typeAndValue.value() // returns Object  of typeAndValue.type()

需要一组“提取器”来应用转换,并且类的使用者必须意识到“对象”返回类型的“歧义性”,但仍然能够消费和使用信息,鉴于其目的。

我当前正在考虑的示例涉及构建 SQL DDL 或 DML,例如使用从评估 csv 文件中的行而派生的列表中的信息的 CREATE Table 语句。

经过更多挖掘,希望能找到一些东西,我写下了我的想法。

请记住,我在这里的目的并不是呈现“完整”的东西,因为我确信这里缺少一些东西,未解决边缘情况等。

pasrse(List<Map<String, String>> rows, List<String> headers例如,这可能是从 Jackson 读取的 CSV 文件中的行样本。

再说一次,这并不完整,所以我不想指出以下所有错误。问题不是“我们如何写这个?”,而是“有人熟悉现有的东西吗?它可以做如下的事情?”。

import gms.labs.cassandra.sandbox.extractors.Extractor;
import gms.labs.cassandra.sandbox.extractors.Extractors;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

@Accessors(fluent=true, chain=true)
public class TypeAndValue
{

    @Builder
    TypeAndValue(Class<?> type, String rawValue){
        this.type = type;
        this.rawValue = rawValue;
        label = "NONE";
    }

    @Getter
    final Class<?> type;

    @Getter
    final String rawValue;

    @Setter
    @Getter
    String label;

    public Object value(){
        return Extractors.extractorFor(this).value(rawValue);
    }

    static final String DEFAULT_LABEL = "NONE";

}

一个简单的解析器,其中 parse来 self 有 List<Map<String,String>> 的上下文来自 CSVReader。

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.math.NumberUtils;

import java.util.*;
import java.util.function.BiFunction;

public class JavaTypeParser
{
public static final List<TypeAndValue> parse(List<Map<String, String>> rows, List<String> headers)
{
    List<TypeAndValue> typesAndVals = new ArrayList<TypeAndValue>();
    for (Map<String, String> row : rows) {
        for (String header : headers) {
            String val = row.get(header);
            TypeAndValue typeAndValue =
                    //  isNull, isBoolean, isNumber
                    isNull(val).orElse(isBoolean(val).orElse(isNumber(val).orElse(_typeAndValue.apply(String.class, val).get())));
            typesAndVals.add(typeAndValue.label(header));
        }
    }
  
}

public static Optional<TypeAndValue> isNumber(String val)
{
    if (!NumberUtils.isCreatable(val)) {
        return Optional.empty();
    } else {
        return _typeAndValue.apply(NumberUtils.createNumber(val).getClass(), val);
    }
}

public static Optional<TypeAndValue> isBoolean(String val)
{
    boolean bool = (val.equalsIgnoreCase("true") || val.equalsIgnoreCase("false"));
    if (bool) {
        return _typeAndValue.apply(Boolean.class, val);
    } else {
        return Optional.empty();
    }
}

public static Optional<TypeAndValue> isNull(String val){
    if(Objects.isNull(val) || val.equals("null")){
        return _typeAndValue.apply(ObjectUtils.Null.class,val);
    }
    else{
        return Optional.empty();
    }
}

static final BiFunction<Class<?>, String, Optional<TypeAndValue>> _typeAndValue = (type, value) -> Optional.of(
        TypeAndValue.builder().type(type).rawValue(value).build());

}

提取器。只是一个示例,说明如何在某处注册值(包含在字符串中)的“提取器”以进行查找。也可以通过多种其他方式引用它们。

import gms.labs.cassandra.sandbox.TypeAndValue;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.math.NumberUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.List;

public class Extractors
{

private static final List<Class> NUMS = Arrays.asList(
        BigInteger.class,
        BigDecimal.class,
        Long.class,
        Integer.class,
        Double.class,
        Float.class);

public static final Extractor<?> extractorFor(TypeAndValue typeAndValue)
{
    if (NUMS.contains(typeAndValue.type())) {
        return (Extractor<Number>) value -> NumberUtils.createNumber(value);
    } else if(typeAndValue.type().equals(Boolean.class)) {
        return  (Extractor<Boolean>) value -> Boolean.valueOf(value);
    } else if(typeAndValue.type().equals(ObjectUtils.Null.class)) {
        return  (Extractor<ObjectUtils.Null>) value -> null; // should we just return the raw value.  some frameworks coerce to null.
    } else if(typeAndValue.type().equals(String.class)) {
        return  (Extractor<String>) value -> typeAndValue.rawValue(); // just return the raw value.  some frameworks coerce to null.
    }
    else{
        throw new RuntimeException("unsupported");
    }
}
}

我从 JavaTypeParser 类中运行了这个,以供引用。

public static void main(String[] args)
{

    Optional<TypeAndValue> num = isNumber("-1230980980980980980980980980980988009808989080989809890808098292");
    num.ifPresent(typeAndVal -> {
        System.out.println(typeAndVal.value());
        System.out.println(typeAndVal.value().getClass());  // BigInteger
    });
    num = isNumber("-123098098097987");
    num.ifPresent(typeAndVal -> {
        System.out.println(typeAndVal.value());
        System.out.println(typeAndVal.value().getClass()); // Long
    });
    num = isNumber("-123098.098097987"); // Double
    num.ifPresent(typeAndVal -> {
        System.out.println(typeAndVal.value());
        System.out.println(typeAndVal.value().getClass());
    });
    num = isNumber("-123009809890898.0980979098098908080987"); // BigDecimal
    num.ifPresent(typeAndVal -> {
        System.out.println(typeAndVal.value());
        System.out.println(typeAndVal.value().getClass());
    });

    Optional<TypeAndValue> bool = isBoolean("FaLse");
    bool.ifPresent(typeAndVal -> {
        System.out.println(typeAndVal.value());
        System.out.println(typeAndVal.value().getClass()); // Boolean
    });

    Optional<TypeAndValue> nulll = isNull("null");
    nulll.ifPresent(typeAndVal -> {
        System.out.println(typeAndVal.value());
        //System.out.println(typeAndVal.value().getClass());  would throw null pointer exception
        System.out.println(typeAndVal.type()); // ObjectUtils.Null (from apache commons lang3)
    });

}

最佳答案

我不知道有哪个库可以做到这一点,也从未见过任何在开放的可能类型集上以这种方式工作的东西。

对于封闭的类型集(您知道所有可能的输出类型),更简单的方法是将类 FQN 写入字符串中(根据您的描述,如果您控制写入的字符串,我没有得到) .
完整的 FQN,or an alias to it .

否则我认为不写所有支票是没有办法的。

此外,当我考虑边缘用例时,它会非常微妙。

假设您在字符串中使用 json 作为序列化格式,您如何区分 String 值(如 Hello World)和写入的 Date采用某种 ISO 格式(例如 2020-09-22)。为此,您需要在所做的检查中引入一些优先级(首先尝试使用某些正则表达式检查它是否是日期,如果不是,则使用下一个,简单字符串将是最后一个)

如果你有两个对象怎么办:

   String name;
   String surname;
}

class Employee {
   String name;
   String surname;
   Integer salary
}

您会收到第二种类型的序列化值,但工资为空(空或属性完全丢失)。

如何区分集合和列表?

我不知道您的意图是否如此动态,或者您已经知道所有可能的反序列化类型,也许问题中的更多详细信息可以有所帮助。

更新

刚刚看到代码,现在看起来更清晰了。 如果您知道所有可能的输出,那就是这样。
我要做的唯一改变是减轻您想要管理的类型的增加,从而抽象提取过程。
为此,我认为应该做一些小的改变,例如:

interface Extractor {
    Boolean match(String value);
    Object extract(String value);
}

然后您可以为每种类型定义一个提取器:

class NumberExtractor implements Extractor<T> {
    public Boolean match(String val) {
        return NumberUtils.isCreatable(val);
    }
    public Object extract(String value) {
        return NumberUtils.createNumber(value);
    }
}
class StringExtractor implements Extractor {
    public Boolean match(String s) {
        return true; //<-- catch all
    }
    public Object extract(String value) {
        return value;
    }
}

然后注册并自动执行检查:

public class JavaTypeParser {
  private static final List<Extractor> EXTRACTORS = List.of(
      new NullExtractor(),
      new BooleanExtractor(),
      new NumberExtractor(),
      new StringExtractor()
  )

  public static final List<TypeAndValue> parse(List<Map<String, String>> rows, List<String> headers) {
    List<TypeAndValue> typesAndVals = new ArrayList<TypeAndValue>();
    for (Map<String, String> row : rows) {
        for (String header : headers) {
            String val = row.get(header);
            
            typesAndVals.add(extract(header, val));
        }
    }
}
  public static final TypeAndValue extract(String header, String value) {
       for (Extractor<?> e : EXTRACTOR) {
           if (e.match(value) {
               Object v = extractor.extract(value);
               return TypeAndValue.builder()
                         .label(header)
                         .value(v) //<-- you can put the real value here, and remove the type field
                         .build()
           }
       }
       throw new IllegalStateException("Can't find an extractor for: " + header + " | " + value);

  }

要解析 CSV,我建议 https://commons.apache.org/proper/commons-csv因为 CSV 解析可能会引发严重问题。

关于java - 有没有办法使用 Jackson 和/或其关联库之一(csv、json 等)将字符串转换为 Java 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63757433/

相关文章:

java - java中方法的引用

java - 不可变的 Jackson ObjectWriter

java - 如何使用 jackson 以不区分大小写的方式从Json对象反序列化为Boolean.class?

c# 字符串到 float 的转换无效?

java - @ControllerAdvice 仅用于集中/全局异常处理或我们可以用它做的任何其他事情?

java - java中的多线程

json - jackson 与双向一对多关系混淆

javascript - 如何使用innerHTML将文本转换为变量名以打印其值?

Ruby:4 字节数组到 int32

java - 我如何在java中通过字节数组旋转图像?