在不知道JSON格式的情况下在Java中parsingJSON

我试图parsingJava中的JSONstring,并find键值对,以便我可以确定JSON对象的近似结构,因为JSONstring的对象结构是未知的。

例如,一个执行可能有一个像这样的JSONstring:

{"id" : 12345, "days" : [ "Monday", "Wednesday" ], "person" : { "firstName" : "David", "lastName" : "Menoyo" } } 

而另一个像这样的:

  {"url" : "http://someurl.com", "method" : "POST", "isauth" : false } 

我将如何循环遍历各种JSON元素并确定键和值? 我看着jackson-coreJsonParser 。 我看到如何抓住下一个“标记”并确定它是什么types的标记(即字段名称,值,数组开始等),但是,我不知道如何获取实际标记的值。

例如:

 public void parse(String json) { try { JsonFactory f = new JsonFactory(); JsonParser parser = f.createParser(json); JsonToken token = parser.nextToken(); while (token != null) { if (token.equals(JsonToken.START_ARRAY)) { logger.debug("Start Array : " + token.toString()); } else if (token.equals(JsonToken.END_ARRAY)) { logger.debug("End Array : " + token.toString()); } else if (token.equals(JsonToken.START_OBJECT)) { logger.debug("Start Object : " + token.toString()); } else if (token.equals(JsonToken.END_OBJECT)) { logger.debug("End Object : " + token.toString()); } else if (token.equals(JsonToken.FIELD_NAME)) { logger.debug("Field Name : " + token.toString()); } else if (token.equals(JsonToken.VALUE_FALSE)) { logger.debug("Value False : " + token.toString()); } else if (token.equals(JsonToken.VALUE_NULL)) { logger.debug("Value Null : " + token.toString()); } else if (token.equals(JsonToken.VALUE_NUMBER_FLOAT)) { logger.debug("Value Number Float : " + token.toString()); } else if (token.equals(JsonToken.VALUE_NUMBER_INT)) { logger.debug("Value Number Int : " + token.toString()); } else if (token.equals(JsonToken.VALUE_STRING)) { logger.debug("Value String : " + token.toString()); } else if (token.equals(JsonToken.VALUE_TRUE)) { logger.debug("Value True : " + token.toString()); } else { logger.debug("Something else : " + token.toString()); } token = parser.nextToken(); } } catch (Exception e) { logger.error("", e); } } 

jackson或其他一些库( gsonsimple-json )中是否有一个类可以生成树,或者允许通过json元素循环访问并获取除了值之外的实际键名?

看看Jacksons内置的树型模型function 。

而你的代码将是:

 public void parse(String json) { JsonFactory factory = new JsonFactory(); ObjectMapper mapper = new ObjectMapper(factory); JsonNode rootNode = mapper.readTree(json); Iterator<Map.Entry<String,JsonNode>> fieldsIterator = rootNode.fields(); while (fieldsIterator.hasNext()) { Map.Entry<String,JsonNode> field = fieldsIterator.next(); System.out.println("Key: " + field.getKey() + "\tValue:" + field.getValue()); } } 

如果不同的库适合你,你可以尝试org.json :

 JSONObject object = new JSONObject(myJSONString); String[] keys = JSONObject.getNames(object); for (String key : keys) { Object value = object.get(key); // Determine type of value and do something with it... } 

使用Gson库为未知的Json对象分析find下面的代码。

 public class JsonParsing { static JsonParser parser = new JsonParser(); public static HashMap<String, Object> createHashMapFromJsonString(String json) { JsonObject object = (JsonObject) parser.parse(json); Set<Map.Entry<String, JsonElement>> set = object.entrySet(); Iterator<Map.Entry<String, JsonElement>> iterator = set.iterator(); HashMap<String, Object> map = new HashMap<String, Object>(); while (iterator.hasNext()) { Map.Entry<String, JsonElement> entry = iterator.next(); String key = entry.getKey(); JsonElement value = entry.getValue(); if (null != value) { if (!value.isJsonPrimitive()) { if (value.isJsonObject()) { map.put(key, createHashMapFromJsonString(value.toString())); } else if (value.isJsonArray() && value.toString().contains(":")) { List<HashMap<String, Object>> list = new ArrayList<>(); JsonArray array = value.getAsJsonArray(); if (null != array) { for (JsonElement element : array) { list.add(createHashMapFromJsonString(element.toString())); } map.put(key, list); } } else if (value.isJsonArray() && !value.toString().contains(":")) { map.put(key, value.getAsJsonArray()); } } else { map.put(key, value.getAsString()); } } } return map; } } 

未知格式的JSON到HashMap

写JSON和阅读Json

 public static JsonParser parser = new JsonParser(); public static void main(String args[]) { writeJson("JsonFile.json"); readgson("JsonFile.json"); } public static void readgson(String file) { try { System.out.println( "Reading JSON file from Java program" ); FileReader fileReader = new FileReader( file ); com.google.gson.JsonObject object = (JsonObject) parser.parse( fileReader ); Set <java.util.Map.Entry<String, com.google.gson.JsonElement>> keys = object.entrySet(); if ( keys.isEmpty() ) { System.out.println( "Empty JSON Object" ); }else { Map<String, Object> map = json_UnKnown_Format( keys ); System.out.println("Json 2 Map : "+map); } } catch (IOException ex) { System.out.println("Input File Does not Exists."); } } public static Map<String, Object> json_UnKnown_Format( Set <java.util.Map.Entry<String, com.google.gson.JsonElement>> keys ){ Map<String, Object> jsonMap = new HashMap<String, Object>(); for (Entry<String, JsonElement> entry : keys) { String keyEntry = entry.getKey(); System.out.println(keyEntry + " : "); JsonElement valuesEntry = entry.getValue(); if (valuesEntry.isJsonNull()) { System.out.println(valuesEntry); jsonMap.put(keyEntry, valuesEntry); }else if (valuesEntry.isJsonPrimitive()) { System.out.println("P - "+valuesEntry); jsonMap.put(keyEntry, valuesEntry); }else if (valuesEntry.isJsonArray()) { JsonArray array = valuesEntry.getAsJsonArray(); List<Object> array2List = new ArrayList<Object>(); for (JsonElement jsonElements : array) { System.out.println("A - "+jsonElements); array2List.add(jsonElements); } jsonMap.put(keyEntry, array2List); }else if (valuesEntry.isJsonObject()) { com.google.gson.JsonObject obj = (JsonObject) parser.parse(valuesEntry.toString()); Set <java.util.Map.Entry<String, com.google.gson.JsonElement>> obj_key = obj.entrySet(); jsonMap.put(keyEntry, json_UnKnown_Format(obj_key)); } } return jsonMap; } @SuppressWarnings("unchecked") public static void writeJson( String file ) { JSONObject json = new JSONObject(); json.put("Key1", "Value"); json.put("Key2", 777); // Converts to "777" json.put("Key3", null); json.put("Key4", false); JSONArray jsonArray = new JSONArray(); jsonArray.put("Array-Value1"); jsonArray.put(10); jsonArray.put("Array-Value2"); json.put("Array : ", jsonArray); // "Array":["Array-Value1", 10,"Array-Value2"] JSONObject jsonObj = new JSONObject(); jsonObj.put("Obj-Key1", 20); jsonObj.put("Obj-Key2", "Value2"); jsonObj.put(4, "Value2"); // Converts to "4" json.put("InnerObject", jsonObj); JSONObject jsonObjArray = new JSONObject(); JSONArray objArray = new JSONArray(); objArray.put("Obj-Array1"); objArray.put(0, "Obj-Array3"); jsonObjArray.put("ObjectArray", objArray); json.put("InnerObjectArray", jsonObjArray); Map<String, Integer> sortedTree = new TreeMap<String, Integer>(); sortedTree.put("Sorted1", 10); sortedTree.put("Sorted2", 103); sortedTree.put("Sorted3", 14); json.put("TreeMap", sortedTree); try { System.out.println("Writting JSON into file ..."); System.out.println(json); FileWriter jsonFileWriter = new FileWriter(file); jsonFileWriter.write(json.toJSONString()); jsonFileWriter.flush(); jsonFileWriter.close(); System.out.println("Done"); } catch (IOException e) { e.printStackTrace(); } } 

你会对jackson的Map满意吗?

 ObjectMapper objectMapper = new ObjectMapper(); Map<String, Object> map = objectMapper.readValue(jsonString, new TypeReference<HashMap<String,Object>>(){}); 

或者也许是一个JsonNode

 JsonNode jsonNode = objectMapper.readTree(String jsonString) 

为了将JSON快速转换为可以“钻取”并使用的Java对象(地图),可以使用json-io( https://github.com/jdereg/json-io )。 这个库将让你阅读一个JSONstring,并取回一个“地图的地图”表示。

如果您的JVM中有相应的Java类,则可以读取JSON并将其直接parsing为Java类的实例。

 JsonReader.jsonToMaps(String json) 

json是包含要读取的JSON的string。 返回值是一个Map,其中键将包含JSON字段,并且值将包含关联的值。

 JsonReader.jsonToJava(String json) 

将读取相同的JSONstring,并且返回值将被序列化为JSON的Java实例。 如果您的JVM中有写入的类,请使用此API

 JsonWriter.objectToJson(MyClass foo). 

下面是我写的一个示例,显示了我如何parsing一个json,并将其中的每个数字都弄乱:

 public class JsonParser { public static Object parseAndMess(Object object) throws IOException { String json = JsonUtil.toJson(object); JsonNode jsonNode = parseAndMess(json); if(null != jsonNode) return JsonUtil.toObject(jsonNode, object.getClass()); return null; } public static JsonNode parseAndMess(String json) throws IOException { JsonNode rootNode = parse(json); return mess(rootNode, new Random()); } private static JsonNode parse(String json) throws IOException { JsonFactory factory = new JsonFactory(); ObjectMapper mapper = new ObjectMapper(factory); JsonNode rootNode = mapper.readTree(json); return rootNode; } private static JsonNode mess(JsonNode rootNode, Random rand) throws IOException { if (rootNode instanceof ObjectNode) { Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields(); while (fieldsIterator.hasNext()) { Map.Entry<String, JsonNode> field = fieldsIterator.next(); replaceObjectNode((ObjectNode) rootNode, field, rand); } } else if (rootNode instanceof ArrayNode) { ArrayNode arrayNode = ((ArrayNode) rootNode); replaceArrayNode(arrayNode, rand); } return rootNode; } private static void replaceObjectNode(ObjectNode rootNode, Map.Entry<String, JsonNode> field, Random rand) throws IOException { JsonNode childNode = field.getValue(); if (childNode instanceof IntNode) { (rootNode).put(field.getKey(), rand.nextInt(1000)); } else if (childNode instanceof LongNode) { (rootNode).put(field.getKey(), rand.nextInt(1000000)); } else if (childNode instanceof FloatNode) { (rootNode).put(field.getKey(), format(rand.nextFloat())); } else if (childNode instanceof DoubleNode) { (rootNode).put(field.getKey(), format(rand.nextFloat())); } else { mess(childNode, rand); } } private static void replaceArrayNode(ArrayNode arrayNode, Random rand) throws IOException { int arrayLength = arrayNode.size(); if(arrayLength == 0) return; if (arrayNode.get(0) instanceof IntNode) { for (int i = 0; i < arrayLength; i++) { arrayNode.set(i, new IntNode(rand.nextInt(10000))); } } else if (arrayNode.get(0) instanceof LongNode) { arrayNode.removeAll(); for (int i = 0; i < arrayLength; i++) { arrayNode.add(rand.nextInt(1000000)); } } else if (arrayNode.get(0) instanceof FloatNode) { arrayNode.removeAll(); for (int i = 0; i < arrayLength; i++) { arrayNode.add(format(rand.nextFloat())); } } else if (arrayNode.get(0) instanceof DoubleNode) { arrayNode.removeAll(); for (int i = 0; i < arrayLength; i++) { arrayNode.add(format(rand.nextFloat())); } } else { for (int i = 0; i < arrayLength; i++) { mess(arrayNode.get(i), rand); } } } public static void print(JsonNode rootNode) throws IOException { System.out.println(rootNode.toString()); } private static double format(float a) { return Math.round(a * 10000.0) / 100.0; } }