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...
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!
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");