JSON to Java Objects, best practice for modeling the json stream

后端 未结 3 1353
心在旅途
心在旅途 2021-01-20 17:58

I have a JSON stream being generated by a server side C++ program that is currently in development. I\'ve been given a sample of the resulting JSON and I am concerned that I

3条回答
  •  北恋
    北恋 (楼主)
    2021-01-20 18:40

    With GSON, assuming that the class you are deserializing into has fields for all the names that appear in the JSON, the fields not found in the JSON will just be left null:

    https://sites.google.com/site/gson/gson-user-guide#TOC-Finer-Points-with-Objects

    "While deserialization, a missing entry in JSON results in setting the corresponding field in the object to null"

    Things get a little more complicated if arbitrary field names are allowed in the JSON - for example, if Point allows c1, c2, ... cn. But you can handle this with a custom deserializer.

    https://sites.google.com/site/gson/gson-user-guide#TOC-Writing-a-Deserializer

    Edit:

    Here's how you might write a custom deserializer for Point:

    private class DateTimeDeserializer implements JsonDeserializer {
        public Point deserialize(JsonElement json, Type typeOfT, 
                JsonDeserializationContext context) throws JsonParseException {
            List parts = Lists.newArrayList();
    
            for(Map.Entry entry : 
                    json.getAsJsonObject().entrySet()) {
                char type = ;
                int index = Integer.parseInt(entry.getKey().substring(1)) - 1;
    
                while(parts.size() <= index) {
                    parts.add(new PointPart());
                }
    
                PointPart part = parts.get(index);
                switch(entry.getKey().charAt(0)) {
                case 'c':
                    part.c = entry.getValue().getAsBoolean();
                    break;
                case 'k':
                    part.k = entry.getValue().getAsInt();
                    break;
                }
            }
    
            return new Point(parts);
        }
    }
    
    class Point {
        List parts;
    
        Point(List parts) {
            this.parts = parts;
        }
    }
    
    class PointPart {
        boolean c;
        int k;
    }
    

提交回复
热议问题