Home  >  Q&A  >  body text

java - How to determine whether null or empty is returned when spring returns json?

Using the @ResponseBody provided by spring, it is very convenient to return the json object.

But one problem is that sometimes it is impossible to determine whether @ResponseBody will return empty("") or null. The questioner made a rough observation. It seems that whether the String in java is null or "", the final result returned through json is "", while for Object, will be returned. null, and 0 will be returned for int type data.

Is the above conclusion correct?

ringa_leeringa_lee2658 days ago928

reply all(3)I'll reply

  • 阿神

    阿神2017-06-14 10:53:24

    This is related to the instance variable type in your pojo and the json library used (the json library can set how to handle null)

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-06-14 10:53:24

    1. When returning POJO, you can encapsulate the business data, such as encapsulating it into the JSONResult class, which contains code, msg, and data. Data is the business data (that is, the POJO instance), code is the status code, and msg is the description. In this way, it can be used as business data When it is empty, just return the error code, so that the returned result is still json format data, which is convenient for the interface caller to process.

    2. Directly return JSON format data, use fastjson or net.sf.json to directly return the JSONObject object, and fill in the business data into the JSONObject object manually or automatically.

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-06-14 10:53:24

    If you use the Jackon library, you can annotate @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) on the pojo. In this case, if a certain attribute value is null or "", the key will not be included when serialized into json

    reply
    0
  • Cancelreply