about JAVA com.alibaba.fastjson.JSONObject class extends, How to correct mistake?

I want to extends com.alibaba.fastjson.JSONObject for new a function,follow is my code,but is wrong. how to correct mistake?

import com.alibaba.fastjson.JSONObject;
public class SJSONObject extends JSONObject {
public String optString(String key) { if (containsKey(key)){ return getString(key); } return "";
}
}

and then i use it:

SJSONObject jsobj =(SJSONObject) JSON.parseObject(sb.toString());
String aa= jsobj.optString("ssss");

it is wrong!

5

1 Answer

You don't have to extend from JSONObject. Do something like this.

public class yourClass { public static String optString(JSONObject json, String key) { if (json.containsKey(key)){ return json.getString(key); } else{ return ""; } }
}

and your client code can be:

JSONObject json = new JSON.parseObject(sb.toString());
String aa= youClass.optString(json, "ssss");

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like