Takichiii
Takichiii

Reputation: 563

Java parse a JSONList which is not formatted as an array

I am struggling with this issue and I can't find an answer anywhere. Ihave a .jsonlist file formatted like this :

example.jsonlist

{"op_author":1, "op_name":2}
{"op_author":3, "op_name":4}
{"op_author":5, "op_name":6}

I would like to parse it into a Java object, but I can't find how to do it with Gson or json-simple libraries since it is not formated like a json object.

Here is what I tried so far :

Modele.java

public class Modele {
    private String op_author, op_name;
}

JsonListToJava.java

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class JsonListToJava {

    public static void main(String[] args) throws IOException {
        try(Reader reader = new InputStreamReader(JsonListToJava.class.getResourceAsStream("example.jsonlist"), "UTF-8")){
            Gson gson = new GsonBuilder().create();
            Modele p = gson.fromJson(reader, Modele.class);
            System.out.println(p);
        }
    }
}

But I get this error :

Exception in thread "main" com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 2 column ...

Upvotes: 1

Views: 435

Answers (1)

Alexey Soshin
Alexey Soshin

Reputation: 17721

JSON libraries are usually designed to work with valid JSONs.

In your case you can read the file line by line, then parse:

try(BufferedReader reader = new BufferedReader(new InputStreamReader(JsonListToJava.class.getResourceAsStream("example.jsonlist"), "UTF-8"))){
    Gson gson = new GsonBuilder().create();
    Stream<String> lines = reader.lines();

    lines.forEach((line) -> {
        Model p = gson.fromJson(line, Model.class);
        System.out.println(p);
    });
}

Upvotes: 1

Related Questions