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

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.

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest