Tuesday, 29 June 2021

Moshi: Set default values to the missing fields

In this post, I am going to explain how to set default values to the missing fields.

 

When reading JSON that is missing a field, Moshi library depends on the default constructor. Whatever the values set by default constructor are used as default values for the missing fields.

 

Let’s see it with an example.

 

Box.java

package com.sample.app.model;

public class Box {
    private Integer width;
    private Integer height;

    public Box() {
        this.width = -1;
        this.height = -1;
    }

    public Box(Integer width, Integer height) {
        super();
        this.width = width;
        this.height = height;
    }

    public Integer getWidth() {
        return width;
    }

    public void setWidth(Integer width) {
        this.width = width;
    }

    public Integer getHeight() {
        return height;
    }

    public void setHeight(Integer height) {
        this.height = height;
    }

    @Override
    public String toString() {
        return "Box [width=" + width + ", height=" + height + "]";
    }

}

 

DefaultValueDemo.java

package com.sample.app;

import java.io.IOException;

import com.sample.app.model.Box;
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;

public class DefaultValueDemo {

    public static void main(String args[]) throws IOException {
        Moshi moshi = new Moshi.Builder().build();

        JsonAdapter<Box> boxJsonAdapter = moshi.adapter(Box.class);

        String json1 = "{\"height\":15,\"width\":10}";
        String json2 = "{\"height\":15}";
        String json3 = "{\"width\":10}";
        String json4 = "{}";

        Box box1 = boxJsonAdapter.fromJson(json1);
        Box box2 = boxJsonAdapter.fromJson(json2);
        Box box3 = boxJsonAdapter.fromJson(json3);
        Box box4 = boxJsonAdapter.fromJson(json4);

        System.out.println(box1);
        System.out.println(box2);
        System.out.println(box3);
        System.out.println(box4);
    }

}

 

Output

Box [width=10, height=15]
Box [width=-1, height=15]
Box [width=10, height=-1]
Box [width=-1, height=-1]

 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment