I want to achieve that I override one method in JSONObject. So it always return a list even if it has one element:
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
public class JSONObjectDecorator extends JSONObject {
public JSONObjectDecorator(JSONObject jsonObject) {
super(jsonObject, JSONObject.getNames(jsonObject));
}
@Override
public List<String> get(String field){
List<String> result = new ArrayList<String>();
if (!isNull(field)) {
Object data = get(field);
if (data instanceof JSONArray) {
JSONArray array = (JSONArray) data;
for (int i=0; i< array.length(); i++){
result.add(array.getString(i));
}
} else {
result.add(data.toString());
}
}
return result;
}
}
Right now this code gives a StackOverflowError because of this line:
Object data = get(field);
How should I achieve this?
UPDATE: I know why it is a StackOverflowError, and as @Andy Turner highlighted super.get solves the constructor issue, but then when I call for example getString() on an instance of the JSONObjectDecorator it throws an exception that the field is not String. (because it is the List, probably "getString" calls "get")
I will check where "get(String field)" called in JSONObject and I think solution will be to override those methods too.