【问题标题】:Get single field from JSON using Jackson使用 Jackson 从 JSON 中获取单个字段
【发布时间】:2014-11-29 05:09:08
【问题描述】:

给定一个任意 JSON,我想获取单个字段 contentType 的值。 Jackson 怎么做?

{
  contentType: "foo",
  fooField1: ...
}

{
  contentType: "bar",
  barArray: [...]
}

相关

【问题讨论】:

标签: java json jackson


【解决方案1】:

杰克逊之路

考虑到您没有描述数据结构的 POJO,您可以简单地这样做:

final String json = "{\"contentType\": \"foo\", \"fooField1\": ... }";
final ObjectNode node = new ObjectMapper().readValue(json, ObjectNode.class);
//                              ^ 
// actually, try and *reuse* a single instance of ObjectMapper

if (node.has("contentType")) {
    System.out.println("contentType: " + node.get("contentType"));
}    

解决 cmets 部分中的问题

但是,如果您不希望使用整个源 String,而只是访问您知道其路径的特定属性,则您必须自己编写它,利用 Tokeniser。


实际上,现在是周末,我有时间,所以我可以先给你一个开始:这是一个基本的!它可以在strict 模式下运行并吐出合理的错误消息,或者在请求无法满足时宽容并返回Optional.empty

public static class JSONPath {

    protected static final JsonFactory JSON_FACTORY = new JsonFactory();

    private final List<JSONKey> keys;

    public JSONPath(final String from) {
        this.keys = Arrays.stream((from.startsWith("[") ? from : String.valueOf("." + from))
                .split("(?=\\[|\\]|\\.)"))
                .filter(x -> !"]".equals(x))
                .map(JSONKey::new)
                .collect(Collectors.toList());
    }

    public Optional<String> getWithin(final String json) throws IOException {
        return this.getWithin(json, false);
    }

    public Optional<String> getWithin(final String json, final boolean strict) throws IOException {
        try (final InputStream stream = new StringInputStream(json)) {
            return this.getWithin(stream, strict);
        }
    }

    public Optional<String> getWithin(final InputStream json) throws IOException {
        return this.getWithin(json, false);
    }

    public Optional<String> getWithin(final InputStream json, final boolean strict) throws IOException {
        return getValueAt(JSON_FACTORY.createParser(json), 0, strict);
    }

    protected Optional<String> getValueAt(final JsonParser parser, final int idx, final boolean strict) throws IOException {
        try {
            if (parser.isClosed()) {
                return Optional.empty();
            }

            if (idx >= this.keys.size()) {
                parser.nextToken();
                if (null == parser.getValueAsString()) {
                    throw new JSONPathException("The selected node is not a leaf");
                }

                return Optional.of(parser.getValueAsString());
            }

            this.keys.get(idx).advanceCursor(parser);
            return getValueAt(parser, idx + 1, strict);
        } catch (final JSONPathException e) {
            if (strict) {
                throw (null == e.getCause() ? new JSONPathException(e.getMessage() + String.format(", at path: '%s'", this.toString(idx)), e) : e);
            }

            return Optional.empty();
        }
    }

    @Override
    public String toString() {
        return ((Function<String, String>) x -> x.startsWith(".") ? x.substring(1) : x)
                .apply(this.keys.stream().map(JSONKey::toString).collect(Collectors.joining()));
    }

    private String toString(final int idx) {
        return ((Function<String, String>) x -> x.startsWith(".") ? x.substring(1) : x)
                .apply(this.keys.subList(0, idx).stream().map(JSONKey::toString).collect(Collectors.joining()));
    }

    @SuppressWarnings("serial")
    public static class JSONPathException extends RuntimeException {

        public JSONPathException() {
            super();
        }

        public JSONPathException(final String message) {
            super(message);
        }

        public JSONPathException(final String message, final Throwable cause) {
            super(message, cause);
        }

        public JSONPathException(final Throwable cause) {
            super(cause);
        }
    }

    private static class JSONKey {

        private final String key;
        private final JsonToken startToken;

        public JSONKey(final String str) {
            this(str.substring(1), str.startsWith("[") ? JsonToken.START_ARRAY : JsonToken.START_OBJECT);
        }

        private JSONKey(final String key, final JsonToken startToken) {
            this.key = key;
            this.startToken = startToken;
        }

        /**
         * Advances the cursor until finding the current {@link JSONKey}, or
         * having consumed the entirety of the current JSON Object or Array.
         */
        public void advanceCursor(final JsonParser parser) throws IOException {
            final JsonToken token = parser.nextToken();
            if (!this.startToken.equals(token)) {
                throw new JSONPathException(String.format("Expected token of type '%s', got: '%s'", this.startToken, token));
            }

            if (JsonToken.START_ARRAY.equals(this.startToken)) {
                // Moving cursor within a JSON Array
                for (int i = 0; i != Integer.valueOf(this.key).intValue(); i++) {
                    JSONKey.skipToNext(parser);
                }
            } else {
                // Moving cursor in a JSON Object
                String name;
                for (parser.nextToken(), name = parser.getCurrentName(); !this.key.equals(name); parser.nextToken(), name = parser.getCurrentName()) {
                    JSONKey.skipToNext(parser);
                }
            }
        }

        /**
         * Advances the cursor to the next entry in the current JSON Object
         * or Array.
         */
        private static void skipToNext(final JsonParser parser) throws IOException {
            final JsonToken token = parser.nextToken();
            if (JsonToken.START_ARRAY.equals(token) || JsonToken.START_OBJECT.equals(token) || JsonToken.FIELD_NAME.equals(token)) {
                skipToNextImpl(parser, 1);
            } else if (JsonToken.END_ARRAY.equals(token) || JsonToken.END_OBJECT.equals(token)) {
                throw new JSONPathException("Could not find requested key");
            }
        }

        /**
         * Recursively consumes whatever is next until getting back to the
         * same depth level.
         */
        private static void skipToNextImpl(final JsonParser parser, final int depth) throws IOException {
            if (depth == 0) {
                return;
            }

            final JsonToken token = parser.nextToken();
            if (JsonToken.START_ARRAY.equals(token) || JsonToken.START_OBJECT.equals(token) || JsonToken.FIELD_NAME.equals(token)) {
                skipToNextImpl(parser, depth + 1);
            } else {
                skipToNextImpl(parser, depth - 1);
            }
        }

        @Override
        public String toString() {
            return String.format(this.startToken.equals(JsonToken.START_ARRAY) ? "[%s]" : ".%s", this.key);
        }
    }
}

假设以下 JSON 内容:

{
  "people": [{
    "name": "Eric",
    "age": 28
  }, {
    "name": "Karin",
    "age": 26
  }],
  "company": {
    "name": "Elm Farm",
    "address": "3756 Preston Street Wichita, KS 67213",
    "phone": "857-778-1265"
  }
}

...您可以按如下方式使用我的JSONPath 类:

    final String json = "{\"people\":[],\"company\":{}}"; // refer to JSON above
    System.out.println(new JSONPath("people[0].name").getWithin(json)); // Optional[Eric]
    System.out.println(new JSONPath("people[1].name").getWithin(json)); // Optional[Karin]
    System.out.println(new JSONPath("people[2].name").getWithin(json)); // Optional.empty
    System.out.println(new JSONPath("people[0].age").getWithin(json));  // Optional[28]
    System.out.println(new JSONPath("company").getWithin(json));        // Optional.empty
    System.out.println(new JSONPath("company.name").getWithin(json));   // Optional[Elm Farm]

请记住,它是基本的。它不强制数据类型(它返回的每个值都是String)并且只返回叶节点。

实际测试用例

它处理InputStreams,因此您可以针对一些巨大的 JSON 文档对其进行测试,发现它比浏览器下载和显示其内容要快得多:

System.out.println(new JSONPath("info.contact.email")
            .getWithin(new URL("http://test-api.rescuegroups.org/v5/public/swagger.php").openStream()));
// Optional[support@rescuegroups.org]

快速测试

请注意,我没有重复使用任何已经存在的 JSONPathObjectMapper,因此结果不准确——这只是一个非常粗略的比较:

public static Long time(final Callable<?> r) throws Exception {
    final long start = System.currentTimeMillis();
    r.call();
    return Long.valueOf(System.currentTimeMillis() - start);
}

public static void main(final String[] args) throws Exception {
    final URL url = new URL("http://test-api.rescuegroups.org/v5/public/swagger.php");
    System.out.println(String.format(   "%dms to get 'info.contact.email' with JSONPath",
                                        time(() -> new JSONPath("info.contact.email").getWithin(url.openStream()))));
    System.out.println(String.format(   "%dms to just download the entire document otherwise",
                                        time(() -> new Scanner(url.openStream()).useDelimiter("\\A").next())));
    System.out.println(String.format(   "%dms to bluntly map it entirely with Jackson and access a specific field",
                                        time(() -> new ObjectMapper()
                                                .readValue(url.openStream(), ObjectNode.class)
                                                .get("info").get("contact").get("email"))));
}

使用 JSONPath 获取 'info.contact.email' 需要 378 毫秒
否则只需 756 毫秒即可下载整个文档
896ms 直言不讳地将其完全与 Jackson 映射并访问特定字段

【讨论】:

  • 问题是如何读取单个字段。映射整个对象绝对是多余的。答案不是问题。
  • 另一个答案是正确的。 Jackson 有两种方案:分别读取字段或映射整个对象。问题是关于第一个问题。
  • @Gangnus:很好!我在哪里可以读到这个?快速谷歌搜索后,我似乎找不到任何信息......我认为第二个答案没有提到Jackson,这是问题中要求的库。它也无法解释您似乎发现的差异!
  • studytrails.com/java/json/java-jackson-introduction。或者寻找 JSONObject 类型——它只是允许你只读取你需要的那部分 json 的类。你是对的 - 对“在杰克逊中阅读单独的字段”进行明智的搜索是行不通的。
  • @Gangnus:你让我对这个问题感兴趣。事实证明,您在 cmets 部分中链接的答案正是您不想要的!它最终委托给mapper.readValue(jp, Foo.class),其中Foo 是一个带注释的POJO……我似乎找不到一个完整的解决方案,它实际上可以让您在不首先解析整个内容的情况下访问特定字段……所以我写了一个。我以为你可能会感兴趣!干杯。
【解决方案2】:

只想在 2019 年更新。我发现以下最容易实现:

//json can be file or String
JsonNode parent= new ObjectMapper().readTree(json);
String content = parent.path("contentType").asText();

我建议使用path 而不是get,因为get 会抛出 NPE,其中路径返回默认值 0 或“”,如果第一次正确设置解析,则使用起来更安全.

我的 0.02 美元

【讨论】:

    【解决方案3】:

    如果您在应用程序中使用 JSON jar,那么以下代码 sn-p 很有用:

    String json = "{\"contentType\": \"foo\", \"fooField1\": ... }";
    JSONObject jsonObject = new JSONObject(json);
    System.out.println(jsonObject.getString("contentType"));
    

    如果您使用的是 Gson jars,那么相同的代码将如下所示:

    Gson gson = new GsonBuilder().create();
    Map jsonMap = gson.fromJson(json, Map.class);
    System.out.println(jsonMap.get("contentType"));
    

    【讨论】:

      【解决方案4】:

      另一种方式是:

      String json = "{\"contentType\": \"foo\", \"fooField1\": ... }";
      JsonNode parent= new ObjectMapper().readTree(json);
      String content = parent.get("contentType").asText();
      

      【讨论】:

        【解决方案5】:

        我的问题有点棘手..对于下面的对象我需要 JSON 字符串..

        下面是我的类,其中有一些字符串和一个 JSON 对象,我们需要在单个表中保存在 DB 中..

        public class TestTransaction extends TestTransaction {
        private String radarId;
        private String exclusionReason;
        private Timestamp eventTs;
        private JSONObject drivingAttributes;
        

        我正在使用对象映射器来转换这个对象,但它在 Json 中给了我一个 Json .. 这是错误的.. 我需要使用下面的映射器将内部 JSON 对象转换为字符串

        public static final ObjectMapper EXCLUSION_OBJECT_MAPPER = new ObjectMapper()
                .setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'+0000'"))
                .setSerializationInclusion(JsonInclude.Include.NON_NULL);
        

        无效的 JSON 是:

            {
            "txnId": "Test1",
            "txnIdDomain": "TEST1",
            "tradeDate": "2019-06-13T08:59:33.000+0000",
            "txnVersion": 0,
            "txnRevision": 0,
            "radarId": "TEST2",
            "exclusionReason": "CurrencyFilter Exclusion reason",
            "eventTs": "2019-07-18T19:03:32.426+0000",
            "drivingAttributes": {
                "Contra currency id": "USD",
                "Dealt currency id": "CAD"
            },
            "validated": false
        }
        

        正确的JSON应该是

        {
            "txnId": "Test1",
            "txnIdDomain": "TEST1",
            "tradeDate": "2019-06-13T08:59:33.000+0000",
            "txnVersion": 0,
            "txnRevision": 0,
            "radarId": "TEST2",
            "exclusionReason": "CurrencyFilter Exclusion reason",
            "eventTs": "2019-07-18T19:03:32.426+0000",
            "drivingAttributes": "Contra currency id:USD, Dealt currency id:CAD",
            "validated": false
        }
        

        【讨论】:

          【解决方案6】:

          当我决定使用 Jackson 作为我从事的项目的 json 库时,我遇到了这个问题;主要是因为它的速度。我已经习惯在我的项目中使用org.jsonGson

          我很快发现,org.jsonGson 中的许多琐碎任务在 Jackson

          中并不那么简单

          所以我编写了以下类来让事情变得更容易。

          下面的类将允许您像使用简单的 org.json 库一样轻松地使用 Jackson,同时仍保留 Jackson 的功能和速度

          我在几个小时内编写了整个代码,因此请随意调试并根据自己的目的调整代码。

          请注意,下面的 JSONObject/JSONArray 将完全符合 OP 的要求。

          第一个是JSONObject,其方法与org.json.JSONObject类似;但实际上运行 Jackson 代码来构建 JSON 并解析 json 字符串。

          import com.fasterxml.jackson.annotation.JsonProperty;
          import com.fasterxml.jackson.core.JsonProcessingException;
          import com.fasterxml.jackson.databind.JsonNode;
          import com.fasterxml.jackson.databind.ObjectMapper;
          import com.fasterxml.jackson.databind.node.ArrayNode;
          import com.fasterxml.jackson.databind.node.JsonNodeFactory;
          import com.fasterxml.jackson.databind.node.ObjectNode;
          import java.io.IOException;
          import java.math.BigDecimal;
          import java.math.BigInteger;
          import java.util.logging.Level;
          import java.util.logging.Logger;
          
          /**
           *
           * @author GBEMIRO JIBOYE <gbenroscience@gmail.com>
           */
          public class JSONObject {
          
              ObjectNode parseNode;
          
              public JSONObject() {
                  this.parseNode = JsonNodeFactory.instance.objectNode(); // initializing     
              }
          
              public JSONObject(String json) throws JsonProcessingException {
                  ObjectMapper mapper = new ObjectMapper();
                  try {
          
                      this.parseNode = mapper.readValue(json, ObjectNode.class);
          
                  } catch (JsonProcessingException ex) {
                      Logger.getLogger(JSONObject.class.getName()).log(Level.SEVERE, null, ex);
                  }
              }
          
              public void put(String key, String value) {
                  parseNode.put("key", value); // building
              }
          
              public void put(String key, boolean value) {
                  parseNode.put("key", value); // building
              }
          
              public void put(String key, int value) {
                  parseNode.put("key", value); // building
              }
          
              public void put(String key, short value) {
                  parseNode.put("key", value); // building
              }
          
              public void put(String key, float value) {
                  parseNode.put("key", value); // building
              }
          
              public void put(String key, long value) {
                  parseNode.put("key", value); // building
              }
          
              public void put(String key, double value) {
                  parseNode.put("key", value); // building
              }
          
              public void put(String key, byte[] value) {
                  parseNode.put("key", value); // building
              }
          
              public void put(String key, BigInteger value) {
                  parseNode.put("key", value); // building
              }
          
              public void put(String key, BigDecimal value) {
                  parseNode.put("key", value); // building
              }
          
              public void put(String key, Object[] value) {
                  ArrayNode anode = parseNode.putArray(key);
                  for (Object o : value) {
                      anode.addPOJO(o); // building 
                  }
              }
          
              public void put(String key, JSONObject value) {
                  parseNode.set(key, value.parseNode);
              }
          
              public void put(String key, Object value) {
                  parseNode.putPOJO(key, value);
              }
          
              public static class Parser<T> {
          
                  public T decode(String json, Class clazz) {
                      try {
                          return new Converter<T>().fromJsonString(json, clazz);
                      } catch (IOException ex) {
                          Logger.getLogger(JSONObject.class.getName()).log(Level.SEVERE, null, ex);
                      }
                      return null;
                  }
          
              }
          
              public int optInt(String key) {
                  if (parseNode != null) {
                      JsonNode nod = parseNode.get(key);
                      return nod != null ? nod.asInt(0) : 0;
                  }
                  return 0;
              }
          
              public long optLong(String key) {
                  if (parseNode != null) {
                      JsonNode nod = parseNode.get(key);
                      return nod != null ? nod.asLong(0) : 0;
                  }
                  return 0;
              }
          
              public double optDouble(String key) {
                  if (parseNode != null) {
                      JsonNode nod = parseNode.get(key);
                      return nod != null ? nod.asDouble(0) : 0;
                  }
                  return 0;
              }
          
              public boolean optBoolean(String key) {
                  if (parseNode != null) {
                      JsonNode nod = parseNode.get(key);
                      return nod != null ? nod.asBoolean(false) : false;
                  }
                  return false;
              }
          
              public double optFloat(String key) {
                  if (parseNode != null) {
                      JsonNode nod = parseNode.get(key);
                      return nod != null && nod.isFloat() ? nod.floatValue() : 0;
                  }
                  return 0;
              }
          
              public short optShort(String key) {
                  if (parseNode != null) {
                      JsonNode nod = parseNode.get(key);
                      return nod != null && nod.isShort() ? nod.shortValue() : 0;
                  }
                  return 0;
              }
          
              public byte optByte(String key) {
                  if (parseNode != null) {
                      JsonNode nod = parseNode.get(key);
          
                      return nod != null && nod.isShort() ? (byte) nod.asInt(0) : 0;
          
                  }
                  return 0;
              }
          
              public JSONObject optJSONObject(String key) {
                  if (parseNode != null) {
                      if (parseNode.has(key)) {
                          ObjectNode nod = parseNode.with(key);
          
                          JSONObject obj = new JSONObject();
                          obj.parseNode = nod;
          
                          return obj;
                      }
          
                  }
                  return new JSONObject();
              }
          
              public JSONArray optJSONArray(String key) {
                  if (parseNode != null) {
                      if (parseNode.has(key)) {
                          ArrayNode nod = parseNode.withArray(key);
          
                          JSONArray obj = new JSONArray();
                          if (nod != null) {
                              obj.parseNode = nod;
                              return obj;
                          }
                      }
          
                  }
                  return new JSONArray();
              }
          
              public String optString(String key) {
                  if (parseNode != null) {
                      JsonNode nod = parseNode.get(key);
                      return parseNode != null && nod.isTextual() ? nod.asText("") : "";
                  }
                  return "";
              }
          
              @Override
              public String toString() {
                  return parseNode.toString();
              }
          
              public String toCuteString() {
                  return parseNode.toPrettyString();
              }
          
          }
          

          这是 JSONArray 等价物的代码,其工作方式类似于 org.json.JSONArray;但使用 Jackson 代码。

          import com.fasterxml.jackson.core.JsonProcessingException;
          import com.fasterxml.jackson.databind.JsonNode;
          import com.fasterxml.jackson.databind.ObjectMapper;
          import com.fasterxml.jackson.databind.node.ArrayNode;
          import com.fasterxml.jackson.databind.node.JsonNodeFactory;
          import com.fasterxml.jackson.databind.node.ObjectNode;
          import java.math.BigDecimal;
          import java.math.BigInteger; 
          
          /**
           *
           * @author GBEMIRO JIBOYE <gbenroscience@gmail.com>
           */
          public class JSONArray {
          
          
              protected ArrayNode parseNode; 
          
              public JSONArray() {
                  this.parseNode = JsonNodeFactory.instance.arrayNode(); // initializing     
              }
          
              public JSONArray(String json) throws JsonProcessingException{
                  ObjectMapper mapper = new ObjectMapper();
          
                      this.parseNode = mapper.readValue(json, ArrayNode.class);
          
              }
          
              public void putByte(byte val) {
                  parseNode.add(val);
              }
          
              public void putShort(short val) {
                  parseNode.add(val);
              }
          
              public void put(int val) {
                  parseNode.add(val);
              }
          
              public void put(long val) {
                  parseNode.add(val);
              }
          
              public void pu(float val) {
                  parseNode.add(val);
              }
          
              public void put(double val) {
                  parseNode.add(val);
              }
          
              public void put(String val) {
                  parseNode.add(val);
              }
          
              public void put(byte[] val) {
                  parseNode.add(val);
              }
          
              public void put(BigDecimal val) {
                  parseNode.add(val);
              }
          
              public void put(BigInteger val) {
                  parseNode.add(val);
              }
          
              public void put(Object val) {
                  parseNode.addPOJO(val);
              }
          
               public void put(int index, JSONArray value) {
                  parseNode.set(index, value.parseNode);
              }
          
                public void put(int index, JSONObject value) {
                  parseNode.set(index, value.parseNode);
              }
          
               public String optString(int index) {
                  if (parseNode != null) {
                      JsonNode nod = parseNode.get(index);
                      return nod != null ? nod.asText("") : "";
                  }
                  return "";
              }
           public int optInt(int index) {
                  if (parseNode != null) {
                      JsonNode nod = parseNode.get(index);
                      return nod != null ? nod.asInt(0) : 0;
                  }
                  return 0;
              }
          
              public long optLong(int index) {
                  if (parseNode != null) {
                      JsonNode nod = parseNode.get(index);
                      return nod != null ? nod.asLong(0) : 0;
                  }
                  return 0;
              }
          
              public double optDouble(int index) {
                  if (parseNode != null) {
                      JsonNode nod = parseNode.get(index);
                      return nod != null ? nod.asDouble(0) : 0;
                  }
                  return 0;
              }
          
              public boolean optBoolean(int index) {
                  if (parseNode != null) {
                      JsonNode nod = parseNode.get(index);
                      return nod != null ? nod.asBoolean(false) : false;
                  }
                  return false;
              }
          
              public double optFloat(int index) {
                  if (parseNode != null) {
                      JsonNode nod = parseNode.get(index);
                      return nod != null && nod.isFloat() ? nod.floatValue() : 0;
                  }
                  return 0;
              }
          
              public short optShort(int index) {
                  if (parseNode != null) {
                      JsonNode nod = parseNode.get(index);
                      return nod != null && nod.isShort() ? nod.shortValue() : 0;
                  }
                  return 0;
              }
          
              public byte optByte(int index) {
                  if (parseNode != null) {
                      JsonNode nod = parseNode.get(index);
          
                      return nod != null && nod.isShort() ? (byte) nod.asInt(0) : 0;
          
                  }
                  return 0;
              }
          
              public JSONObject optJSONObject(int index) {
                  if (parseNode != null) {
                      JsonNode nod = parseNode.get(index);
          
                      if(nod != null){
                          if(nod.isObject()){
                                  ObjectNode obn = (ObjectNode) nod;
                                    JSONObject obj = new JSONObject();
                                    obj.parseNode = obn;
                                    return obj;
                             }
          
                      }
          
                  }
                  return new JSONObject();
              }
          
                public JSONArray optJSONArray(int index) {
                  if (parseNode != null) {
                      JsonNode nod = parseNode.get(index);
          
                      if(nod != null){
                          if(nod.isArray()){
                                  ArrayNode anode = (ArrayNode) nod;
                                    JSONArray obj = new JSONArray();
                                    obj.parseNode = anode;
                                    return obj;
                             }
          
                      }
          
                  }
                  return new JSONArray();
              }
          
                   @Override
              public String toString() {
                  return parseNode.toString();
              }
                public String toCuteString() {
                  return parseNode.toPrettyString();
              }
          
          
          }
          

          最后,为了将 Java 类编码和解码为 JSON,我添加了这个简单的类:

          /**
           *
           * @author GBEMIRO JIBOYE <gbenroscience@gmail.com>
           */
          public class Converter<T> {
              // Serialize/deserialize helpers
          
              private Class clazz;
          
              public Converter() {}
          
              public T fromJsonString(String json , Class clazz) throws IOException {
                  this.clazz = clazz;
                  return getObjectReader().readValue(json);
              }
          
              public String toJsonString(T obj) throws JsonProcessingException {
                  this.clazz = obj.getClass();
                  return getObjectWriter().writeValueAsString(obj);
              }
          
              private ObjectReader requestReader;
              private ObjectWriter requestWriter;
          
              private void instantiateMapper() {
                  ObjectMapper mapper = new ObjectMapper()
                          .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
          
          
          
                  requestReader = mapper.readerFor(clazz);
                  requestWriter = mapper.writerFor(clazz);
              }
          
              private ObjectReader getObjectReader() {
                  if (requestReader == null) {
                      instantiateMapper();
                  }
                  return requestReader;
              }
          
              private ObjectWriter getObjectWriter() {
                  if (requestWriter == null) {
                      instantiateMapper();
                  }
                  return requestWriter;
              }
          
          
          
          }
          

          现在来品尝(测试)酱汁(代码),使用以下方法:

          import com.fasterxml.jackson.annotation.JsonProperty;
          import com.fasterxml.jackson.core.JsonProcessingException;
          import java.util.logging.Level;
          import java.util.logging.Logger;
          
          /**
           *
           * @author GBEMIRO JIBOYE <gbenroscience@gmail.com>
           */
          public class SimplerJacksonTest {
          
          
              static class Credentials {
          
                  private String userName;
                  private String uid;
                  private String password;
                  private long createdAt;
          
                  public Credentials() {
                  }
          
                  public Credentials(String userName, String uid, String password, long createdAt) {
                      this.userName = userName;
                      this.uid = uid;
                      this.password = password;
                      this.createdAt = createdAt;
                  }
          
                  @JsonProperty("userName")
                  public String getUserName() {
                      return userName;
                  }
          
                  @JsonProperty("userName")
                  public void setUserName(String userName) {
                      this.userName = userName;
                  }
          
                  @JsonProperty("uid")
                  public String getUid() {
                      return uid;
                  }
          
                  @JsonProperty("uid")
                  public void setUid(String uid) {
                      this.uid = uid;
                  }
          
                  @JsonProperty("password")
                  public String getPassword() {
                      return password;
                  }
          
                  @JsonProperty("password")
                  public void setPassword(String password) {
                      this.password = password;
                  }
          
                  @JsonProperty("createdAt")
                  public long getCreatedAt() {
                      return createdAt;
                  }
          
                  @JsonProperty("createdAt")
                  public void setCreatedAt(long createdAt) {
                      this.createdAt = createdAt;
                  }
          
                  public String encode() {
                      try {
                          return new Converter<Credentials>().toJsonString(this);
                      } catch (JsonProcessingException ex) {
                          Logger.getLogger(Credentials.class.getName()).log(Level.SEVERE, null, ex);
                      }
                      return null;
                  }
          
                  public Credentials decode(String jsonData) {
                      try {
                          return new Converter<Credentials>().fromJsonString(jsonData, Credentials.class);
                      } catch (Exception ex) {
                          Logger.getLogger(Converter.class.getName()).log(Level.SEVERE, null, ex);
                      }
                      return null;
                  }
          
              }
          
          
              public static JSONObject testJSONObjectBuild() {
                  JSONObject obj = new JSONObject();
          
                  Credentials cred = new Credentials("Adesina", "01eab26bwkwjbak2vngxh9y3q6", "xxxxxx1234", System.currentTimeMillis());
                  String arr[] = new String[]{"Boy", "Girl", "Man", "Woman"};
                  int nums[] = new int[]{0, 1, 2, 3, 4, 5};
          
                  obj.put("creds", cred);
                  obj.put("pronouns", arr);
                  obj.put("creds", cred);
                  obj.put("nums", nums);
          
                  System.out.println("json-coding: " + obj.toCuteString());
          
                  return obj;
              }
          
              public static void testJSONObjectParse(String json) {
                  JSONObject obj;
                  try {
                      obj = new JSONObject(json);
          
                      JSONObject credsObj = obj.optJSONObject("creds");
          
                      String userName = credsObj.optString("userName");
                      String uid = credsObj.optString("uid");
                      String password = credsObj.optString("password");
                      long createdAt = credsObj.optLong("createdAt");
          
          
                      System.out.println("<<---Parse Results--->>");
                      System.out.println("userName = " + userName);
                      System.out.println("uid = " + uid);
                      System.out.println("password = " + password);
                      System.out.println("createdAt = " + createdAt);
          
          
                  } catch (JsonProcessingException ex) {
                      Logger.getLogger(JSONObject.class.getName()).log(Level.SEVERE, null, ex);
                  }
          
              }
          
                 public static JSONArray testJSONArrayBuild() {
          
                   JSONArray array = new JSONArray();
                  array.put(new Credentials("Lawani", "001uadywdbs", "ampouehehu", System.currentTimeMillis()));
          
                  array.put("12");
                  array.put(98);
                  array.put(Math.PI);
                  array.put("Good scores!");
          
                  System.out.println("See the built array: "+array.toCuteString());
          
                  return array;
          
              }
          
          
                 public static void testJSONArrayParse(String json) {
          
                  try {
                      JSONArray array = new JSONArray(json);
          
          
                      JSONObject credsObj = array.optJSONObject(0);
          
                      //Parse credentials in index 0
          
                      String userName = credsObj.optString("userName");
                      String uid = credsObj.optString("uid");
                      String password = credsObj.optString("password");
                      long createdAt = credsObj.optLong("createdAt");
          
          
                      //Now return to the  main array and parse other entries
          
                      String twelve = array.optString(1);
                      int ninety = array.optInt(2);
                      double pi = array.optDouble(3);
                      String scoreNews = array.optString(4);
          
          
                      System.out.println("Parse Results");
                      System.out.println("userName = " + userName);
                      System.out.println("uid = " + uid);
                      System.out.println("password = " + password);
                      System.out.println("createdAt = " + createdAt);
          
          
                      System.out.println("Parse Results");
                      System.out.println("index 1 = " + twelve);
                      System.out.println("index 2 = " + ninety);
                      System.out.println("index 3 = " + pi);
                      System.out.println("index 4 = " + scoreNews);
          
          
                  } catch (JsonProcessingException ex) {
                      Logger.getLogger(JSONObject.class.getName()).log(Level.SEVERE, null, ex);
                  }
          
              }
          
          
                 public static String testCredentialsEncode(){
                      Credentials cred = new Credentials("Olaoluwa", "01eab26bwkwjbak2vngxh9y3q6", "xxxxxx1234", System.currentTimeMillis());
          
                      String encoded = cred.encode();
                      System.out.println("encoded credentials = "+encoded);
                      return encoded;
                 }
          
                  public static Credentials testCredentialsDecode(String json){
                      Credentials cred = new Credentials().decode(json);
          
          
                      System.out.println("encoded credentials = "+cred.encode());
          
          
                      return cred;
                 }
          
          
              public static void main(String[] args) {
          
                 JSONObject jo = testJSONObjectBuild();
                  testJSONObjectParse(jo.toString());
          
                  JSONArray ja = testJSONArrayBuild();
          
                  testJSONArrayParse(ja.toString());
          
                  String credsJSON = testCredentialsEncode();
          
                  testCredentialsDecode(credsJSON);
          
              }
          
          }
          

          要在某个地方获取源代码,而不必在此处复制源代码,请参阅:

          the code on Github

          【讨论】:

            猜你喜欢
            • 2016-12-08
            • 2018-12-23
            • 2014-05-11
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-10-18
            • 1970-01-01
            相关资源
            最近更新 更多