用于将json转换为键值对中的文本的java代码

时间:2015-09-28 13:05:32

标签: java json

我是Java的新手,我想编写一个代码,将传入的json文件转换为键值对中的文本,这些文本将被管道分隔。 json文件中的模式往往会发生变化。所以我不能根据每个值编写一个程序(我之前尝试过)。

有人可以帮忙吗?

文件是:

[{"type_id":4102,"id":0,"product_name":"ATP:Endpoint","feature_name":"ATP:Endpoint",
"feature_ver":"2014.2.0","atpProtocol":"av","device_uid":"D00A9450ABD85ACD2B0125968FEABBF9","device_ip":"10.75.81.205","device_name":"10.75.81.205","file":{"name":"CSIDL_PROFILE\\desktop\\av ping\\malheur_34_0\\malheur_34_0 - copy (4)","folder":"CSIDL_PROFILE\\desktop\\aving\\malheur_34_0","sha2":"BC44F53958886E6B220CA6C634D78703220139
E968719A7459B859954CAA4A77","md5":null,"version":null,"size":null,"date_created":null,"date_modified":null,"date_accessed":null},"platform":{"processor":"x86 Family 6 Model 45 Stepping 7","country":"1","language":"English","system":"Windows 7 build 7601 Service Pack 1","scanner":"Symantec Endpoint Protection 12.1.3.0"},"scan":{"signatures_version":"20141112.002","technology":"AV Engine"}]

2 个答案:

答案 0 :(得分:1)

我已经编写了一些方法来将json字符串解析为map / list对象。

public static Map<String,Object> parseJSONObjectToMap(JSONObject jsonObject) throws JSONException{
    Map<String, Object> mapData = new HashMap<String, Object>();
    Iterator<String> keysItr = jsonObject.keys();
        while(keysItr.hasNext()) {
            String key = keysItr.next();
            Object value = jsonObject.get(key);

            if(value instanceof JSONArray) {
                value = parseJSONArrayToList((JSONArray) value);
            }else if(value instanceof JSONObject) {
                value = parseJSONObjectToMap((JSONObject) value);
            }
            mapData.put(key, value);
        }
    return mapData;
}

public static List<Object> parseJSONArrayToList(JSONArray array) throws JSONException {
    List<Object> list = new ArrayList<Object>();
    for(int i = 0; i < array.length(); i++) {
        Object value = array.get(i);
        if(value instanceof JSONArray) {
            value = parseJSONArrayToList((JSONArray) value);
        }else if(value instanceof JSONObject) {
            value = parseJSONObjectToMap((JSONObject) value);
        }
        list.add(value);
    }
    return list;
}

答案 1 :(得分:0)

所以我编写了一些通用的有用代码,用于将每个json文件输入转换为管道分隔。此外,这将读取子节点和...请看看并测试自己。我认为这对其他人有用。

package test;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.Iterator;
import java.util.Map;

import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;

public class ParseSEPEvents {

String endTime;
long latestLiveVisitStartTime;
boolean foundLatestVisitEndTime = false;

public ParseSEPEvents() {
}

public static void main(String args[]) throws Exception{
    ParseSEPEvents obj = new ParseSEPEvents();
    String contents = new String(Files.readAllBytes(Paths.get("<FileLocation>")));

    int idx = contents.indexOf("json");
    String jsonStr = contents.substring(idx+5);
    String header = contents.substring(0, idx+5);
    StringBuilder returnStr = obj.logParser(jsonStr);
    StringBuilder fnlStr = new StringBuilder(header).append(returnStr);

    System.out.println(fnlStr);
}

private StringBuilder parseToken( JsonNode node) {
    StringBuilder event = new StringBuilder();

    if (node == null) {
        return event;
    }       

    Iterator<Map.Entry<String, JsonNode>> itr = node.fields();      
    while (itr.hasNext()) {
        Map.Entry<String, JsonNode> keyValue = itr.next();
        String keyStr = keyValue.getKey();
        JsonNode innerNode = node.findValue(keyStr);            

        if(innerNode.isValueNode()){
        event.append(keyValue.getKey()).append("|").append(innerNode.toString()).append("|");
        }else{
            StringBuilder eventChild = parseToken(innerNode);
            event.append(keyValue.getKey()).append("[").append(eventChild).append("]");
        }

    }

    return event;

}

public StringBuilder logParser(String jsonStr) {
    JsonParser parser = null;
    StringBuilder strBuild = new StringBuilder();

    try {
        JsonFactory factory = new MappingJsonFactory();
        System.out.println("Parsing file records.");
        parser = factory.createParser(jsonStr);

        JsonToken currentToken = parser.nextToken();
        if (currentToken != JsonToken.START_ARRAY) {
            System.out.println("Warning: root should be object. quiting.");
            return strBuild;
        }

        while ((parser.nextToken()) != JsonToken.END_ARRAY) {
            currentToken = parser.nextToken();
            JsonNode node = parser.readValueAsTree();

            StringBuilder event = new StringBuilder();
            event = parseToken(node);
            return new StringBuilder("|").append(event);
        }

    } catch (JsonParseException jpe) {
        System.out.println("Unable to parse json records."
                + jpe.getMessage());
    } catch (IOException ioe) {
        System.out.println("Error while parsing file. " + ioe.getMessage());
    } finally {
        try {
            if ((parser != null) && !(parser.isClosed())) {
                parser.close();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
             }
         }

    return strBuild;
     }

}