1

I am new to Java, I want to write a code which convert my incoming json file to text in key-value pair which will be pipe separated. The schema in json files tends to change. So I can't write a program based on each value (which I tried earlier).

Can someone help?

The file is:

[{"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"}]
3

2 Answers 2

4

I have written some methods to parse json string into map/list object.

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

If you use non-standard libraries you should at least point out the dependencies (i.e. libraries to use).
Yup,thanks for reminder You need to import following library mvnrepository.com/artifact/org.json/json/20150729
0

So I have written some universal kinda code that will be used convert every json file input to pipe separated. Also this will read the sub node and... please have a look and test yourself. I think this will be useful for others.

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;
     }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.