How do I expose data in a JSON format through a web service using Java?

后端 未结 9 1882
攒了一身酷
攒了一身酷 2021-01-30 14:23

Is there an easy way to return data to web service clients in JSON using java? I\'m fine with servlets, spring, etc.

9条回答
  •  遇见更好的自我
    2021-01-30 15:07

    We have been using Flexjson for converting Java objects to JSON and have found it very easy to use. http://flexjson.sourceforge.net

    Here are some examples:

    public String searchCars() {
      List cars = carsService.getCars(manufacturerId);
      return new JSONSerializer().serialize(cars);
    }
    

    It has some cool features such as deepSerialize to send the entire graph and it doesn't break with bi directional relationships.

    new JSONSerializer().deepSerialize(user); 
    

    Formatting dates on the server side is often handy too

    new JSONSerializer().transform(
      new DateTransformer("dd/MM/yyyy"),"startDate","endDate"
    ).serialize(contract);
    

提交回复
热议问题