Charles Brown
Charles Brown

Reputation: 927

How to handle Java return JSONObject variable type if it can be an Array or a String

I try to parse a JSON file using Alibaba Fastjson Java library.

One of the JSONObject of the file is either an Array or a String.

Below is the Java snippet

@JSONField(name="States")
private Object[] states;

This can be used when the JSONObject is an array but it will throw an exception when the return type is a String.

Any idea what should I do. The variable type = Object[] seems not good enough.

Upvotes: -1

Views: 201

Answers (1)

Ryuzaki L
Ryuzaki L

Reputation: 40078

@JSONField This annotation also can be used on setter method

 @JSONField(name="states")
 public void setStates(Object states) {

   if(states instanceof String[]) {
        String[] statesArray = (String[]) states;
        this.states = statesArray;
    } else {
        this.states = new String[] {states.toString()};
    }
 }

Upvotes: 0

Related Questions