【发布时间】:2016-05-03 03:34:03
【问题描述】:
我正在编写一个程序,它接受来自客户端的以下格式的 JSON 输入:
{
"campaignID": 1,
"clientID": 1,
"pmapID": 1,
"ward": "1-Bedded (Private)",
"age": 20,
"attr1": "EXA1(A)",
"attr2": "EO",
"attr3": "11/02/2012",
"attr4": "SIN",
"attr5": "N",
"attr6": "Y"
}
我想读取 JSON 输入,将所有属性保存到局部变量(String、int、...)中,最后以 POST("JSON") 响应,它将返回单个浮点/双精度值(例如 {"PMC": 30.12} )。
public class RestletApplication extends Application
{
@Override
public synchronized Restlet createInboundRoot()
{
Router router = new Router(getContext());
router.attach("/pmc/calculate", PMCResource.class);
return router;
}
}
到目前为止,我已经编写了该函数,但不知道如何读取 JSON 输入:
public class PMCResource extends ServerResource
{
@Post("JSON")
public Representation post(Representation entity) throws ResourceException {
try {
if (entity.getMediaType().isCompatible(MediaType.APPLICATION_JSON))
{
// Read JSON file and parse onto local variables
// Do processing & return a float value
}
} catch (Exception e) {
getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
}
}
}
2016 年 5 月 5 日 - 编辑了资源类
// Imports
public class PMCResource extends ServerResource
{
static Logger LOGGER = LoggerFactory.getLogger(PMCResource.class);
@Override
@Post("JSON")
public Representation post(Representation entity) throws ResourceException
{
PMCMatrixDAO matrix = new PMCMatrixDAOImpl();
JsonObjectBuilder response = Json.createObjectBuilder();
try
{
if (entity.getMediaType().isCompatible(MediaType.APPLICATION_JSON))
{
InputStream is = new FileInputStream(getClass().getResource("/input.json").getFile());
try (JsonReader reader = Json.createReader(is)) {
JsonObject obj = reader.readObject();
double result = matrix.calculatePMC(obj);
response.add("PMC", result);
}
}
} catch (Exception e) {
getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
}
return new StringRepresentation(response.build().toString());
}
}
实现类
public class PMCMatrixDAOImpl implements PMCMatrixDAO
{
public double calculatePMC(JsonObject obj)
{
int campaignID = obj.getInt("campaignID");
int clientID = obj.getInt("clientID");
int pmapID = obj.getInt("pmapID");
String ward = obj.getString("ward");
int age = obj.getInt("age");
String attr1 = obj.getString("attr1");
String attr2 = obj.getString("attr2");
String attr3 = obj.getString("attr3");
String attr4 = obj.getString("attr4");
String attr5 = obj.getString("attr5");
String attr6 = obj.getString("attr6");
// SQL processing
double dPMC = sqlQueryCall(...);
return dPMC;
}
}
【问题讨论】:
-
您的 JSON 数据是否包含在您的
Representation实体中? -
对不起@aribeiro,我不太明白你的问题。你能用外行的话解释一下,让这个新手可以理解吗?
-
好吧,您只是想读取您的 JSON 文件,您将评论放在哪里?或者您想知道如何执行包含上述内容的 POST 请求?
-
@aribeiro 将 JSON 文件解析为局部变量后,我将执行 SQL 查询以从数据库中检索值(十进制)。然后我必须将此值作为 JSON 发布回客户端,以便他们可以在门户上显示它。
标签: json rest maven jakarta-ee restlet