Search code examples
javajsongson

Convert a Json file to a class objects but it's in a weird format


Hello so this is my code:

public class Fencers{
    private String name,nation;
    private int id;

    public Fencers(String name, String nation,int id) {
        this.name = name;
        this.nation = nation;
        this.id = id;
    }

    @Override
    public String toString() {
        return
                id+" "+name+" "+nation+"\n";
    }
}

and this is the main :

class Main{
    public static void main(String[] args){
         String json = "{\"name\":\"m\",\"nation\":\"egy\",\"id\":100}{\"name\":\"342\",\"nation\":\"egy\",\"id\":120}"
    }
}

I want to turn json to a class object but it gives me errors because it's in the weird format what to do :palmface:


Solution

  • So there are two issues here:

    1. How should the conversion be done from json to java object? For example, using jackson (ObjectMapper)?
    2. The json in the example is not valid:
    {"name":"m","nation":"egy","id":100}{"name":"342","nation":"egy","id":120}
    

    So before it can be converted from json to a java object, it has to be valid json.

    Why the weird format? Can it be fixed at the source? If yes, (2) is solved, get valid json from wherever it has to be read from. If not, it has to be converted into valid json by your program first before deserializing the json into a java object with a library such as jackson.

    If it's up to your program to convert the input into valid json before deserializing, assuming that all records have the format given in the example, and assuming that the key/value pairs won't contain parentheses or brackets, a really quick fix is a helper method, something like:

    static String toValidJson(String in) {
        return "[" + in.replace("}{", "},{") + "]";
    }
    

    The idea here is to put a comma between objects and close the whole thing in an array. Then it can be deserialized as appropriate into an array, list, etc.

    Edit

    The Gson library is being used for parsing, so putting it all together, it should look something like:

    class Main {
        public static void main(String[] args) {
            // raw data
            String raw = "{\"name\":\"m\",\"nation\":\"egy\",\"id\":100}{\"name\":\"342\",\"nation\":\"egy\",\"id\":120}";
    
            // valid json
            String json = toValidJson(raw);
    
            // parse it
            Gson gson = new Gson();
            Fencers[] fencers = gson.fromJson(json, Fencers[].class);
    
            // do something with the array of fencers
            for (Fencer f : fencers) {
                // ...
            }
        }
    
        static String toValidJson(String in) {
            return "[" + in.replace("}{", "},{") + "]";
        }
    }