代码之家  ›  专栏  ›  技术社区  ›  Cheok Yan Cheng

在单个库中同时获取jsonObject和google gson功能

  •  1
  • Cheok Yan Cheng  · 技术社区  · 14 年前

    我想知道,有没有JSON库可以让我

    1. 从JSON字符串中获取值映射的键( JSONObject 能够这样做)
    2. 从JSON字符串中获取Java对象 Google Gson 能够这样做)

    以下两种印刷品 value

    package jsontest;
    
    import com.google.gson.Gson;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    /**
     *
     * @author yccheok
     */
    public class Main {
    
        public static class Me {
            public String key;
        }
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) throws JSONException {
    
            final String s = "{\"key\" : \"value\"}";
    
            // Feature 1
            final JSONObject jsonObject = new JSONObject("{\"key\" : \"value\"}");
            System.out.println(jsonObject.getString("key"));
    
            // Feature 2
            Gson gson = new Gson();
            Me me = gson.fromJson(s, Me.class);
            System.out.println(me.key);
        }
    }
    

    目前,我必须使用两个不同的库来完成上述与JSON相关的任务。是否有任何库可以同时执行这两个任务?

    2 回复  |  直到 14 年前
        1
  •  4
  •   Colin Hebert    14 年前

    你可以使用 Jackson .

    它有一个 databinding solution (像GSON)和 tree model view (像jsonObject)

    import org.codehaus.jackson.JsonNode;
    import org.codehaus.jackson.map.ObjectMapper;
    
    import java.io.IOException;
    
    public class Main {
    
        public static class Me {
            public String key;
        }
    
        public static void main(String[] args) throws IOException {
            ObjectMapper mapper = new ObjectMapper();
            String json = "{\"key\" : \"value\"}";
    
            // Feature 1
            JsonNode rootNode = mapper.readValue(json, JsonNode.class);
            System.out.println(rootNode.get("key").getTextValue());
    
            // Feature 2
            Me value = mapper.readValue(json, Me.class);
            System.out.println(value.key);
        }
    }
    
        2
  •  3
  •   ColinD    14 年前

    我不知道我是怎么第一次错过这个的,但是你可以在GSON使用它 JsonParser :

     JsonParser parser = new JsonParser();
     JsonElement rootElement = parser.parse(reader);
    

    先前的答案 (不需要这样做)

    我不确定GSON是否有更简单的内置方式来实现这一点,但这似乎有效:

    public enum JsonElementDeserializer implements JsonDeserializer<JsonElement> {
      INSTANCE;
    
      public JsonElement deserialize(
          JsonElement json, Type typeOfT, JsonDeserializationContext context) 
          throws JsonParseException {
        return json;
      }
    }
    

    然后:

    Gson gson = new GsonBuilder().registerTypeAdapter(JsonElement.class,
        JsonElementDeserializer.INSTANCE).create();
    JsonElement rootElement = gson.fromJson(reader, JsonElement.class);