How do you greedily extract JSON in java using the GSON library?

Viewed 75

In this link, the author goes through how to use the GSON library for Java. The main example shows how to parse a json file called "staff.json" shown below:

{
  "name": "mkyong",
  "age": 35,
  "position": [
    "Founder",
    "CTO",
    "Writer"
  ],
  "skills": [
    "java",
    "python",
    "node",
    "kotlin"
  ],
  "salary": {
    "2018": 14000,
    "2012": 12000,
    "2010": 10000
  }
}

The following Java code can read the file, parse it, and create a "Staff" Java object with all the above data loaded, finally printing the java object called "staff" with a lower-case "s":

import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

public class GsonExample2 {

    public static void main(String[] args) {

        Gson gson = new Gson();

        try (Reader reader = new FileReader("c:\\projects\\staff.json")) {

            // Convert JSON File to Java Object
            Staff staff = gson.fromJson(reader, Staff.class);
            
            // print staff object
            System.out.println(staff);

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

    }

}

Running the above code gives the following output:

Staff{name='mkyong', age=35, position=[Founder, CTO, Writer], skills=[java, python, node, kotlin], salary={2018=14000, 2012=12000, 2010=10000}}

Suppose I append the following to "staff.json" so that it looks like this:

{
  "name": "mkyong",
  "age": 35,
  "position": [
    "Founder",
    "CTO",
    "Writer"
  ],
  "skills": [
    "java",
    "python",
    "node",
    "kotlin"
  ],
  "salary": {
    "2018": 14000,
    "2012": 12000,
    "2010": 10000
  }
}
\x00\x0d;ldlk4jkladsfl;kmasdlk\d\g\sd===dsafdsfagf\dgas56yjghg\dafd\g\dfa
fdsaffdas]\fg\n\n\n\n\n\n\n\\t\t\t\t\t\t\\\\\s
adfdgt\\\g\\\fdgdf\sg\df<-----END OF FILE HERE NOW

As you can see, I'm basically appending a bunch of garbage that is clearly not in Json format.

My question: Assuming you don't know much json-formatted data is in the file (i.e. the skills could have hundreds of items in there), how do I modify the Java code above to extract as much json as possible and disregard the garbage I appended in the new staff.json file? The goal is to get the exact same output shown above from the first staff.json input file.

0 Answers
Related