简体   繁体   中英

Unable to parse json object from log file in java

I am learning Java. I have a sample log file which contains key pairs and it values. I am suppose to find a key pair and it's value from certain lines. For example, if line starts with "x" read that line and find it. I am able to get key pairs and it's value in output file but unable to get json object which is at end of line. Goal is to take text file as input and find if sentence starts with particular word. If yes, find key pairs & values from that line and include json object (if any)

Task: Find a line starting with "[Student info]" & parse student id, class status, input (which is json object). Sometimes input may be empty too.

I already checked other questions on this platform including this but didn't help much.

**Input file.**

[King] 9 AM America -- kingNumber 1234567890 -- address: abc/cd/ef -- birthmonth: unknown Input={||Ouptut={}
[born time] 9 AM London -- kingNumber 1234567890 -- address: abc/cd/ef -- birthmonth: unknown Input={||Ouptut={}
[Student info] -- 12/08/2011 -- StudentId: 124421 -- Phonenumber: 4252076406 -- ClassStatus: Senior -- "Random String..." Input={ || Ouput={}
[born time] 9 AM London -- kingNumber 1234567890 -- address: abc/cd/ef -- birthmonth: unknown Input={||Ouptut={}
[Student info] -- 12/08/2011 -- StudentId: 1234567 -- Phonenumber: 4252076406 -- ClassStatus: Senior -- "Random String..." Input={
"kaju": [{
        "Sno": {
            "type": "literal",
            "value": "random"
        }
    }]
}

[Game] 9 AM London -- kingNumber 1234567890 -- address: abc/cd/ef -- birthmonth: unknown Input={
[Student info] -- 12/08/2011 -- StudentId: 1234567 -- Phonenumber: 4252076406 -- ClassStatus: Senior -- "Random String..." Input={ || Ouput={
"core": [{
    "id": {
        "datatype": "https://www.w3schools.com/",
        "type": "website",
        "value": "study"
    },
    "entity": {
        "type": "url",
        "value": "https://www.w3schools.com/"
    },
    "Sno": {
        "type": "literal",
        "value": "random"
    }
}]
}

**Expected Output File**

[Student info] -- 12/08/2011 -- StudentId: 124421 -- Phonenumber: 4252076406 -- ClassStatus: Senior -- "Random String..." Input={ || Ouput={}
[Student info] -- 12/08/2011 -- StudentId: 1234567 -- Phonenumber: 4252076406 -- ClassStatus: Senior -- "Random String..." Input={
"kaju": [{
        "Sno": {
            "type": "literal",
            "value": "random"
        }
    }]
}
[Student info] -- 12/08/2011 -- StudentId: 1234567 -- Phonenumber: 4252076406 -- ClassStatus: Senior -- "Random String..." Input={ || Ouput={
"core": [{
    "id": {
        "datatype": "https://www.w3schools.com/",
        "type": "website",
        "value": "study"
    },
    "entity": {
        "type": "url",
        "value": "https://www.w3schools.com/"
    },
    "Sno": {
        "type": "literal",
        "value": "random"
    }
}]
}

**Current Output File**

[Student info] -- 12/08/2011 -- StudentId: 124421 -- Phonenumber: 4252076406 -- ClassStatus: Senior -- "Random String..." Input={ || Ouput={}
[Student info] -- 12/08/2011 -- StudentId: 1234567 -- Phonenumber: 4252076406 -- ClassStatus: Senior -- "Random String..." Input={
[Student info] -- 12/08/2011 -- StudentId: 1234567 -- Phonenumber: 4252076406 -- ClassStatus: Senior -- "Random String..." Input={ || Ouput={

As you can see from above text files, I am able only able to extract the lines I want (student info) but I am unable to get the json object attached to it. I am looking to abstract json object too (if available). In this case new line always begins with "[".

Note:

  1. There is no guarantee that line [student info] occurs at specific line or specific number of times in file.
  2. There can be n number other lines with other information but all that matters is "student info" line and their json if any.

Below is my code.

public class Kickstarter {

public static void main (String... args) {
    Scanner scan = new Scanner(Kickstarter.class.getResourceAsStream("sample.txt"));
    List<String> fileByLine = new ArrayList<>();
    List<StudentInfo> result = new ArrayList<>();

    while(scan.hasNextLine()) {
        fileByLine.add(scan.nextLine());
    }
    for (Iterator<String> iterator = fileByLine.iterator(); iterator.hasNext();) {
        String line = iterator.next();
        if (!line.startsWith("[Student info]")) {
            iterator.remove();
        }
    }

    for (int i = 0; i < fileByLine.size(); i++) {
        System.out.println(fileByLine.get(i));

    }
}
}

Another file

import com.google.gson.JsonObject;

public class StudentInfo {
   public String studentinfo;
   public boolean isBasic;
   public JsonObject json;
   public String jsonStringBuildUp;

   public StudentInfo (String studentinfo, boolean isBasic) {
       this.studentinfo = studentinfo;
       this.isBasic = isBasic;
       this.json = null;
       this.jsonStringBuildUp = "";
   }

}
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;

import com.google.gson.Gson;

public class KickStarter {

    private static final String STUDENT_INFO = "[Student info]";
    private Map<String, StudentInfo> lineJsonMap;
    private String key;
    private StringBuilder jsonBuilder;

    public static void main(String... args) {
        new KickStarter().scan();
    }

    private void scan() {

        Scanner scan = new Scanner(KickStarter.class.getClassLoader().getResourceAsStream("sample.txt"));
        lineJsonMap = new HashMap<String, StudentInfo>();
        jsonBuilder = null;
        key = null;

        while (scan.hasNextLine()) {

            String line = scan.nextLine();
            if (!line.startsWith("[")) {
                if (jsonBuilder == null) {
                    jsonBuilder = new StringBuilder();
                    jsonBuilder.append("{");
                }
                jsonBuilder.append(line.trim());
            } else if (line.startsWith(STUDENT_INFO)) {
                extractJSON();
                lineJsonMap.put(line, null);
                key = line;
            } else if (line.startsWith("[")) {
                extractJSON();
            }
        }
        extractJSON();
        scan.close();

        // Finally Print values

        Set<Entry<String, StudentInfo>> entrySet = lineJsonMap.entrySet();
        for (Entry<String, StudentInfo> entry : entrySet) {
            System.out.println(entry.getKey());
            StudentInfo value = entry.getValue();
            if (value != null) {
                Gson gson = new Gson();
                System.out.println(gson.toJson(value));
            }
        }
    }

    private void extractJSON() {

        if (key != null) {
            StudentInfo fromJson = null;
            if (jsonBuilder != null) {
                Gson gson = new Gson();
                fromJson = gson.fromJson(jsonBuilder.toString(), StudentInfo.class);
            }
            lineJsonMap.put(key, fromJson);
            key = null;
            jsonBuilder = null;
        }
    }
}

You need to create POJO classes like below.

StudentInfo.java

public class StudentInfo {
    private Core[] core;
    private Kaju[] kaju;

    public Core[] getCore() {
        return core;
    }

    public void setCore(Core[] core) {
        this.core = core;
    }

    @Override
    public String toString() {
        return "ClassPojo [core = " + core + "][kaju = " + kaju + "]";
    }

    public Kaju[] getKaju() {
        return kaju;
    }

    public void setKaju(Kaju[] kaju) {
        this.kaju = kaju;
    }
}

Core.java

public class Core {

    private Id id;
    private Entity entity;
    private Sno Sno;

    public Id getId() {
        return id;
    }

    public void setId(Id id) {
        this.id = id;
    }

    public Entity getEntity() {
        return entity;
    }

    public void setEntity(Entity entity) {
        this.entity = entity;
    }

    public Sno getSno() {
        return Sno;
    }

    public void setSno(Sno Sno) {
        this.Sno = Sno;
    }

    @Override
    public String toString() {
        return "ClassPojo [id = " + id.toString() + ", entity = " + entity.toString() + ", Sno = " + Sno.toString() + "]";
    }
}

Id.java

public class Id {

    private String value;
    private String datatype;
    private String type;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String getDatatype() {
        return datatype;
    }

    public void setDatatype(String datatype) {
        this.datatype = datatype;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    @Override
    public String toString() {
        return "ClassPojo [value = " + value + ", datatype = " + datatype + ", type = " + type + "]";
    }
}

Kaju.java

public class Kaju {

    private Sno Sno;

    public Sno getSno() {
        return Sno;
    }

    public void setSno(Sno Sno) {
        this.Sno = Sno;
    }

    @Override
    public String toString() {
        return "ClassPojo [Sno = " + Sno + "]";
    }
}

Entity.java

public class Entity {

    private String value;
    private String type;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    @Override
    public String toString() {
        return "ClassPojo [value = " + value + ", type = " + type + "]";
    }
}

Sno.java

public class Sno {
    private String value;
    private String type;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    @Override
    public String toString() {
        return "ClassPojo [value = " + value + ", type = " + type + "]";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM