All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.adgear.anoa.read.MapReader Maven / Gradle / Ivy

package com.adgear.anoa.read;

import com.adgear.anoa.AnoaJacksonTypeException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

class MapReader extends AbstractReader> {

  final AbstractReader valueElementReader;
  final Function fn;

  MapReader(AbstractReader valueElementReader) {
    this(valueElementReader, s -> s);
  }

  MapReader(AbstractReader valueElementReader, Function fnKey) {
    this.valueElementReader = valueElementReader;
    this.fn = fnKey;
  }

  @Override
  protected Map read(JsonParser jacksonParser) throws IOException {
    if (jacksonParser.getCurrentToken() == JsonToken.START_OBJECT) {
      Map result = new HashMap<>();
      doMap(jacksonParser, (k, p) -> result.put(fn.apply(k), valueElementReader.read(p)));
      return result;
    } else {
      gobbleValue(jacksonParser);
      return null;
    }
  }

  @Override
  protected Map readStrict(JsonParser jacksonParser)
      throws AnoaJacksonTypeException, IOException {
    switch (jacksonParser.getCurrentToken()) {
      case VALUE_NULL:
        return null;
      case START_OBJECT:
        Map result = new HashMap<>();
        doMap(jacksonParser, (k, p) -> result.put(fn.apply(k), valueElementReader.readStrict(p)));
        return result;
      default:
        throw new AnoaJacksonTypeException("Token is not '{': " + jacksonParser.getCurrentToken());
    }
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy