如何创建一个Java方法来解析一个大的JSON文件

如何创建一个Java方法来解析一个大的JSON文件,java,json,parsing,iterator,jackson,Java,Json,Parsing,Iterator,Jackson,我正在尝试使用Jackson库解析的内容 我想要的是生成一个java方法来获取它的所有键和值,但到目前为止,在我的代码中,我只获取JSON文件的第一个键和第一个值 下面是我用来指导创建自己的Java类的代码片段: public void parse(String json) { JsonFactory factory = new JsonFactory(); ObjectMapper mapper = new ObjectMapper(factory); JsonNo

我正在尝试使用Jackson库解析的内容

我想要的是生成一个java方法来获取它的所有键和值,但到目前为止,在我的代码中,我只获取JSON文件的第一个键和第一个值

下面是我用来指导创建自己的Java类的代码片段:

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());
    }
}
package jsontoxml;

import java.io.*;

import org.json.simple.parser.JSONParser;
import org.json.simple.*;
import java.util.*;


public class JacksonStreamExample {

   public static void main(String[] args) {
       JSONParser parser = new JSONParser();
     try {
        Object obj = parser.parse(new FileReader("text.json"));
        JSONObject jsonObject = (JSONObject) obj;

        JSONArray cells = (JSONArray) jsonObject.get("cells");
        Iterator<JSONObject> iterator = cells.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }

     } catch (Exception e) {

      e.printStackTrace();

     }

  }

}
公共空解析(字符串json){
JsonFactory工厂=新的JsonFactory();
ObjectMapper mapper=新的ObjectMapper(工厂);
JsonNode rootNode=mapper.readTree(json);
迭代器fieldsIterator=rootNode.fields();
while(fieldsIterator.hasNext()){
Map.Entry field=fieldsIterator.next();
System.out.println(“Key:+field.getKey()+”\tValue:+field.getValue());
}
}
我创建的Java类如下所示:

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class JacksonStreamExample {
    public static void main(String[] args) {
        try {
            //Create a JsonFactory instance
            JsonFactory factory = new JsonFactory();

            //Create a JsonParser instance to read from file c:\\text.json
            JsonParser jParser = factory.createJsonParser(new File("c:\\text.json"));

            /*Create an ObjectMapper instance to provide a pointer
             * to root node of the tree after reading the JSON
             */
            ObjectMapper mapper = new ObjectMapper(factory);

            //Create tree from JSON
            JsonNode rootNode = mapper.readTree(jParser);  

            Iterator<Map.Entry<String,JsonNode>> fieldsIterator = rootNode.getFields();
            while (fieldsIterator.hasNext()) {
                Map.Entry<String,JsonNode> field = fieldsIterator.next();
                System.out.println("Key: " + field.getKey() + "\tValue:" + field.getValue());
            }

            jParser.close();

        } catch (JsonGenerationException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
导入java.io.File;
导入java.io.IOException;
导入java.util.Iterator;
导入java.util.Map;
导入org.codehaus.jackson.json工厂;
导入org.codehaus.jackson.jsongGenerationException;
导入org.codehaus.jackson.JsonNode;
导入org.codehaus.jackson.JsonParser;
导入org.codehaus.jackson.map.JsonMappingException;
导入org.codehaus.jackson.map.ObjectMapper;
公共类Jacksonstreame示例{
公共静态void main(字符串[]args){
试一试{
//创建一个JsonFactory实例
JsonFactory工厂=新的JsonFactory();
//创建一个JsonParser实例以从文件c:\\text.json读取
JsonParser jParser=factory.createJsonParser(新文件(“c:\\text.json”);
/*创建ObjectMapper实例以提供指针
*读取JSON后,将其复制到树的根节点
*/
ObjectMapper mapper=新的ObjectMapper(工厂);
//从JSON创建树
JsonNode rootNode=mapper.readTree(jParser);
迭代器fieldsIterator=rootNode.getFields();
while(fieldsIterator.hasNext()){
Map.Entry field=fieldsIterator.next();
System.out.println(“Key:+field.getKey()+”\tValue:+field.getValue());
}
jParser.close();
}捕获(JsonGenerationException e){
e、 printStackTrace();
}捕获(JsonMappingException e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
}
}
我的Eclipse输出如下,它只创建1对(键值):

Key:cells Value:[{“type”:“basic.Circle”,“size”:{“width”:90,“height”:54},“position”:{“x”:-80,“y”:200},“angle”:0,“id”:“cae4c219-c2cd-4a4b-b50c-0f269963ca24”,“embeddes”:“z”:1,“wi_name”:“START”,“wi_描述”:“wi_连接”:“wi_连接”:“wi_分割”,“wi_性能角色”:“wi_预期活动时间”:null,“用户wi_时间”:null,“wi_最大活动时间”:null,“wi_初始延迟”:null,“wi_时间单位”:“秒”,“wi_所需的_和_连接转换”:null,“wi_自定义页面”:“属性”:{“圆圈”:{“填充”:“{”圆圈“{”填充“:”{”宽度“:50,“高度”:30,“笔划宽度”:1,“笔划数组”:“0”},“文本”:{“字体大小”:10,“文本”:“开始”,“填充”:“ffffff”,“字体系列”:“Arial 000000,“笔划宽度”:0,“字体重量”:400}}},{“类型”:“基本圆”,“大小”:{“宽度”:90,“高度”:54},“位置”:{“x”:210,“y”:200},“角度”:0,“id”:“d23133e0-e516-4f72-8127-292545d3d479”,“嵌入”:“z”:2,“wi_名称”:“结束”,“wi_显示名称”:“结束”,“wi_描述”:“wi_连接”,“wi_分割”,“wi_性能角色”:“wi_预期空活动时间”wi_预期用户时间:null,“wi_最大活动时间”:null,“wi_初始延迟”:null,“wi_时间单位”:“秒”,“wi_所需的用户时间”和“连接”:null,“wi_自定义页面”:“属性”:{“圆”:{“填充”:“000000”,“宽度”:50,“高度”:30,“笔划宽度”:1,“笔划数组”:“0”),“文本”:{“字体大小”:10,“文本”:“结束”,“填充”:“Arial FFFF”,“字体系列”:笔划“#000000”,“笔划宽度”:0,“字体重量”:400}}},{“类型”:“基本.矩形”,“位置”:{“x”:-80,“y”:370},“大小”:{“宽度”:90,“高度”:54},“角度”:0,“id”:“a53898a5-c018-45c4-bd3f-4ea4d69f58ed”,“嵌入”:“z”:3,“WIU名称”:“活动1”,“WIU显示名称”:“活动1”,“WIU描述”:“WIU连接”,“WIU拆分”:“wi”:“wi执行”:wi_预期活动时间:null,“wi_预期用户时间”:null,“wi_最大活动时间”:null,“wi_初始延迟”:null,“wi_时间单位”:“秒”,“wi_所需转换”和“wi_连接”:null,“wi_自定义页面”:“属性”:{“rect”:{“宽度”:50,“高度”:30,“rx”:2,“ry”:2,“笔划宽度”:1,“笔划数组”:“0”},“文本”:“活动”,“字体大小”:10,”字体系列“:”Arial“,”stroke“:”000000“,”stroke width“:”0,“font weight“:”400}}},“{”type“:”basic.Rect“,”position“,”x“:”220,“y“:”370},“size“,”size“,”宽度“,”高度“:”54},“角度“,”0,“id“:”e2bd21f2-508d-44b9-9f68-e374d4fa87ea“,”嵌入“,”z“,”4,“wi名称“:”活动2“,”wi显示名称“,”wi显示名称“:”活动2“,”wi描述“,”wi连接“,”wi拆分“:”wi_performingRole“:”wi_预期活动时间“:”null,“wi_预期用户时间“:”null,“wi_最大活动时间“:”null,“wi_初始延迟“:”null,“wi_时间单位“:”秒“,”wi_预期活动时间“:”null,“wi_自定义页面“:”ATTR“:{”rect:{“宽度”:50,“高度”:30,“rx”:2,“工作方式”:2,“笔划宽度”:1,“笔划数组”:“0”;“文本”:“{”文本“:”“,”字体大小“:10,”字体系列“:”Arial“,”笔划“:”000000“,”笔划宽度“:”0“,”字体重量“:”400}}},{”类型“:”链接“,”来源“{”id“:”cae4c219-c2cd-4a4b-b50c-0f269963ca24“}”,目标“:{”id“:”d23133e0-e516-4f72-8127-292545d3d479“}”,路由器“{”名称“:”曼哈顿“}”,标签“{”位置“:”0.5,“属性“:”文本名“{”文本}”“60ee7ff7-3a3b-487d-b581-49027E7BEBEB4”,“嵌入“,”z“,”ATTR“,”标记源“,”d“,”M 10 0 0 L 0 5 L 10 10 10 z“,”转换“,”标度(0.001)”,”标记目标“,”M 10 0 L 0 5 L 10 10 10 z“,”连接“,”笔划“,”黑色“,”类型“,”链接“,”源“,”id“,”A538A598A5 5-c018-45c4-bd3f-EA4D69F5ED“,”目标“,”BD4E468E28F458E”,”id“,”FAB468D“,”路由器:{“名称”:“曼哈顿”},“标签”:[{“位置”:0.5,“属性”:{“文本”:{“tex”
//Create a JsonFactory instance
JsonFactory factory = new JsonFactory();

//Create a JsonParser instance to read from file c:\\text.json
JsonParser jParser = factory.createJsonParser(new File("c:\\text.json"));

/*Create an ObjectMapper instance to provide a pointer
 *to root node of the tree after reading the JSON
 */
ObjectMapper mapper = new ObjectMapper(factory);

//Create tree from JSON
JsonNode rootNode = mapper.readTree(jParser);  


Iterator<Map.Entry<String,JsonNode>> fieldsIterator = rootNode.getFields();
while (fieldsIterator.hasNext()) {

    Map.Entry<String,JsonNode> field = fieldsIterator.next();
    System.out.println("Key: " + field.getKey() + "\tValue:" + field.getValue());
}
Iterator<String> fieldNameIterator = rootNode.getFieldNames();

while (fieldNameIterator.hasNext()) {
    String fieldName = fieldNameIterator.next();
    JsonNode fieldValue = rootNode.getFieldValue(fieldName);

    System.out.println("Key: " + fieldName + "\tValue:" + fieldValue);
}
public static void main(String[] args) {
    try {
        Map source = (new ObjectMapper()).readValue(new File(
                "C:\\json.txt"), Map.class);

        Map<String, Object> result = new LinkedHashMap<>();
        buildFlattenedMap(result, source, null);
        for (String s : result.keySet()) {
             System.out.println(s);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

private static void buildFlattenedMap(Map<String, Object> result,
        Map<String, Object> source, String path) {
    for (Map.Entry<String, Object> entry : source.entrySet()) {
        String key = entry.getKey();
        if (hasText(path)) {
            if (key.charAt(0) == '[') {
                key = StringUtils.join(path, key);
            } else {
                key = StringUtils.join(path, '.', key);
            }
        }
        Object value = entry.getValue();
        if (value instanceof String) {
            result.put(key, value);
        } else if (value instanceof Map) {
            // Need a compound key
            @SuppressWarnings("unchecked")
            Map<String, Object> map = (Map<String, Object>) value;
            buildFlattenedMap(result, map, key);
        } else if (value instanceof Collection) {
            // Need a compound key
            @SuppressWarnings("unchecked")
            Collection<Object> collection = (Collection<Object>) value;
            int count = 0;
            for (Object object : collection) {
                buildFlattenedMap(result, Collections.singletonMap("["
                        + (count++) + "]", object), key);
            }
        } else {
            result.put(key, value == null ? StringUtils.EMPTY : value);
        }
    }
}

private static boolean hasText(CharSequence str) {
    if (StringUtils.isEmpty(str)) {
        return false;
    }
    int strLen = str.length();
    for (int i = 0; i < strLen; i++) {
        if (!Character.isWhitespace(str.charAt(i))) {
            return true;
        }
    }
    return false;
}
package jsontoxml;

import java.io.*;

import org.json.simple.parser.JSONParser;
import org.json.simple.*;
import java.util.*;


public class JacksonStreamExample {

   public static void main(String[] args) {
       JSONParser parser = new JSONParser();
     try {
        Object obj = parser.parse(new FileReader("text.json"));
        JSONObject jsonObject = (JSONObject) obj;

        JSONArray cells = (JSONArray) jsonObject.get("cells");
        Iterator<JSONObject> iterator = cells.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }

     } catch (Exception e) {

      e.printStackTrace();

     }

  }

}