在Java中,你可以使用以下方法返回JSON数据给前端:
import org.json.JSONObject; public class Main { public static void main(String[] args) { JSONObject json = new JSONObject(); json.put("name", "John"); json.put("age", 25); String jsonString = json.toString(); System.out.println(jsonString); } } import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class MainController { @GetMapping("/data") @ResponseBody public String getData() { DataObject data = new DataObject("John", 25); return data.toString(); } } import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class MainController { @GetMapping("/data") public DataObject getData() { return new DataObject("John", 25); } } 请注意,上述示例中的DataObject类是一个自定义的Java类,它可以通过定义相应的属性和方法来表示你要返回的JSON数据。