Я унаследовал веб-проект, который начал подрядчик. Я и мои сотрудники не знакомы с используемой технологией и имеют ряд вопросов. Из того, что мы можем сказать, это, похоже, какой-то RESTful Java-серверный код, но я понимаю, что существует множество различных типов сервисов Java RESTful. Какой из них? Конкретные вопросы:Возврат JSON из кода сервера RESTful Java?
1) Где мы можем узнать больше (особенно вводную информацию) об этой конкретной услуге?
2) Код создает и возвращает JSON через какой-то «волшебный» ... Я просто возвращаю класс модели (код ниже), который имеет методы getter и setter для своих полей, и он автоматически преобразуется в JSON , Я хотел бы узнать больше о том, как это делается автоматически.
3) У нас уже есть код, который создает JSON. Мы должны вернуть это, используя эту структуру. Если я уже есть JSON, как я могу его вернуть? Я пробовал что-то вроде этого:
String testJSON = "{\" menu \ ": {\" id \ ": \" file \ ", \" value \ ": \" Hello there \ "}}"; return testJSON;
вместо того, чтобы возвращать объект модели с геттерами/сеттерами, но это возвращает буквальную текстовую строку, а не JSON. Есть ли способ вернуть фактический JSON, который уже является строкой JSON, и отправить его как JSON?
Вам не нужно отвечать на все вышеперечисленные вопросы. Любые/все указатели в полезном направлении оценены!
КОД
Во-первых, контроллер представления, который возвращает JSON:
package com.aimcloud.server;
import com.aimcloud.util.MySqlConnection;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.FormParam;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.aimcloud.models.SubscriptionTierModel;
@Path("subscription_tier")
public class SubscriptionTierController
{
// this method will return a list of subscription_tier table entries that are currently active
@GET
@Produces({ MediaType.APPLICATION_JSON })
public String/*ArrayList<SubscriptionTierModel>*/ getSubscriptionTiers(@QueryParam("includeActiveOnly") Boolean includeActiveOnly)
{
MySqlConnection mysql = MySqlConnection.getConnection();
ArrayList<SubscriptionTierModel> subscriptionTierArray = new ArrayList<SubscriptionTierModel>();
String queryString;
if (includeActiveOnly)
queryString = "SELECT * FROM subscription_tier WHERE active=1";
else
queryString = "SELECT * FROM subscription_tier";
List<Map<String, Object>> resultList = mysql.query(queryString, null);
for (Map<String, Object> subscriptionRow : resultList)
subscriptionTierArray.add(new SubscriptionTierModel(subscriptionRow));
// String testJSON = "{\"menu\": {\"id\": \"file\", \"value\": \"Hello there\"}}";
// return testJSON;
return subscriptionTierArray;
}
}
Далее, модель код выше возвращений:
package com.aimcloud.models;
// NOTE this does NOT import Globals
import java.sql.Types;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.json.JSONObject;
import com.aimcloud.util.LoggingUtils;
public class SubscriptionTierModel extends ModelPrototype
{
private String name;
private Integer num_studies;
private Integer cost_viewing;
private Integer cost_processing;
private Integer active;
protected void setupFields()
{
this.fields.add("name");
this.fields.add("num_studies");
this.fields.add("cost_viewing");
this.fields.add("cost_processing");
this.fields.add("active");
}
public SubscriptionTierModel()
{
super("subscription");
this.setupFields();
}
public SubscriptionTierModel(Map<String, Object> map)
{
super("subscription");
this.setupFields();
this.initFromMap(map);
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setNum_Studies(Integer num_studies) {
this.num_studies = num_studies;
}
public Integer getNum_studies() {
return this.num_studies;
}
public void setCost_viewing(Integer cost_viewing) {
this.cost_viewing = cost_viewing;
}
public Integer getCost_viewing() {
return this.cost_viewing;
}
public void setCost_processing(Integer cost_processing) {
this.cost_processing = cost_processing;
}
public Integer getCost_processing() {
return this.cost_processing;
}
public void setActive(Integer active) {
this.active = active;
}
public Integer getActive() {
return this.active;
}
}
public abstract class ModelPrototype {
protected MySqlConnection mysql;
protected ArrayList<String> fields;
protected String table;
protected Integer id = null;
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
abstract protected void setupFields();
public ModelPrototype() {
mysql = MySqlConnection.getConnection();
this.fields = new ArrayList<String>();
this.fields.add("id");
}
public void initFromDbResult(List<Map<String, Object>> result) {
if (result.size() >= 1)
{
Map<String, Object> userRow = result.get(0);
this.initFromMap(userRow);
if (result.size() > 1)
{
Thread.dumpStack();
}
}
else
{
throw new WebApplicationException(ServerUtils.generateResponse(Response.Status.NOT_FOUND, "resource not found"));
}
}
protected void initFromMap(Map<String, Object> map) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
Object value = entry.getValue();
// LoggingUtils.log(entry.getKey() + " " + entry.getValue().toString());
if (value != null && this.fields.contains(entry.getKey())) {
this.setField(entry.getKey(), value);
}
}
}
....
Предлагаемые чтения: [Учебное пособие по Java EE - Веб-службы - Глава 29, «Создание веб-служб RESTful с помощью JAX-RS»] (https://docs.oracle.com/javaee/7/tutorial/jaxrs.htm# GIEPU) и [Учебник Java EE - 19.5 JSON в Java EE RESTful Web Services] (https://docs.oracle.com/javaee/7/tutorial/jsonp005.htm) – compuhosny