簡體   English   中英

Java代碼將JSON轉換為鍵值對中的文本

[英]java code to convert json into text in key value pair

我是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"}]

我已經寫了一些方法將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;
}

因此,我編寫了一些通用的kinda代碼,該代碼將用於將每個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;
     }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM