Search code examples
javajsonstringpojo

Create JSON from a plain string using pojo


I have a plain string in java as given below

Roll: 1
Name: john
Roll: 2
Name: jack
Roll: 3
Roll: 4
Name: julie

See here for roll 3 name is missing,

I want to convert above string to a json like given below,

{ "block":[ { "Roll":"1", "Name":"john" }, { "Roll":"2", "Name":"jack" }, { "Roll":"4", "Name":"julie" } ] }

how can I achieve it using java, gson and pojo.


Solution

  • here's what i suggest:

    import java.util.ArrayList;
    import java.util.List;
    import com.google.gson.Gson;
    
    public class Test {
        public static void main(String[] args) {
            Gson gson = new Gson();
            String s = "Roll: 1\nName: john\nRoll: 2\nName: jack\nRoll: 3\nRoll: 4\nName: julie";
            String[] values = s.split("\n");
            List<Obj> objects = new ArrayList<Obj>();
            for(int i = 0; i < values.length - 1; i++){
                Obj o = new Obj(0, null);
                if(values[i].startsWith("Roll")){
                    o.Roll = Integer.parseInt(values[i].split(":")[1].trim());
                    if(values[i + 1].startsWith("Name")){
                        o.Name = values[i + 1].split(":")[1];
                        i++;
                    } else {
                        o.Name = null;
                    }
                }
                objects.add(o);
            }
            EndResult result = new EndResult();
            result.block = new Obj[objects.size()];
            for(int i = 0; i < objects.size(); i++){
                result.block[i] = objects.get(i);
            }
            System.out.println(gson.toJson(result));
        }
    }
    
    class EndResult{
        Obj[] block;
    }
    
    class Obj{
        int Roll;
        String Name;
    
        Obj(int Roll, String Name){
            this.Roll = Roll;
            this.Name = Name;
        }
    }