Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse all jsons that are concatenated in one string in Java

Tags:

java

json

jackson

I have a number of json objects concatenated into one string, and need to parse all of them. Simple example:

String jsonStr = "{"name":"peter","age":40}{"name":"laura","age":50}"

When using an ObjectMapper of jackson to parse this, it finds and reads the first json correctly, and drops the rest of the string.

ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = objectMapper.readTree(jsonStr);
System.out.println(rootNode);

Gives output {"name":"peter","age":20}

Is there any way (in Jackson or another framework) of e.g. returning the number of read characters, or the rest of the string, or an array of JsonNodes?

I found questions with the same goal in JavaScript and in Python, where it was recommended to split by }{ or regex to reformat this to a json array, but I still hope for a more elegant solution.

like image 668
Bastian35022 Avatar asked Oct 22 '25 01:10

Bastian35022


1 Answers

You don't need to modify your input as suggested by others, just use below code.

Main Method

public static void main(String[] args) throws IOException {

    ObjectMapper mapper = new ObjectMapper();
    JsonFactory factory = new JsonFactory(mapper);

    JsonParser parser = factory.createParser(new File("config.json"));
    // factory.createParser(String) and many other overload methods
    // available, byte[], char[], InputStream etc.

    Iterator<Person> persons = parser.readValuesAs(Person.class);
    while(persons.hasNext()) {
        Person p = persons.next();
        System.out.printf("%s: %d%n", p.getName(), p.getAge());
    }
}

Person Class

public class Person {

    private String name;
    private int age;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}  

config.json file

{"name":"peter","age":40}{"name":"laura","age":50}

Program Output

peter: 40
laura: 50

Library used

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.9.5</version>
</dependency>
like image 78
Pratapi Hemant Patel Avatar answered Oct 24 '25 14:10

Pratapi Hemant Patel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!