使用Jackson从JSON获取单个字段

sauutmhj  于 2023-08-08  发布在  其他
关注(0)|答案(5)|浏览(162)

给定一个任意的JSON,我想得到单个字段contentType的值。如何与Jackson合作?

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

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

字符串

相关

wribegjk

wribegjk1#

Jackson之路
假设您没有描述数据结构的POJO,您可以简单地这样做:

final String json = "{\"contentType\": \"foo\", \"fooField1\": ... }";
final JsonNode node = new ObjectMapper().readTree(json);
//                    ^^^^^^^^^^^^^^^^^^
// n.b.: try and *reuse* a single instance of ObjectMapper in production

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

字符串

在评论部分解决问题

但是,如果您不希望使用整个源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),只返回叶节点。

实际测试用例

它处理InputStream s,所以你可以用一些巨大的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 ms
756 ms,否则只下载整个文档
896 ms直接将其与Jackson完全Map并访问特定字段

ukxgm1gy

ukxgm1gy2#

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

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

字符串
我建议使用path而不是get,因为get抛出了一个NPE,其中path返回默认值为0或“",如果第一次正确设置解析,那么使用这会更安全。
我的0.02美元

5cg8jx4n

5cg8jx4n3#

如果您在应用程序中使用JSON jar,那么下面的代码片段很有用:

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"));

sigwle7e

sigwle7e4#

另一种方法是:

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

字符串

9cbw7uwe

9cbw7uwe5#

当我决定使用 * 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

相关问题