ibm mobilefirst Adapter - 将JSONObject转换为POJO类

时间:2017-03-22 09:26:21

标签: json ibm-mobilefirst mobilefirst-adapters mobilefirst-server

任何人都知道 - 如何将JSONObject转换为POJO类?

我创建了一个适配器,我希望在将它发送给客户端之前将其转换为Pojo。

1)我的ResourceAdapterResource.java(适配器)

@POST
@Path("profiles/{userid}/{password}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public JSONObject getStatus(@PathParam("userid") String userid, @PathParam("password") String password) throws IOException {

    Map<String, Object> maps = new HashMap<String,Object>();
            map.put("userid", userid);
            map.put("password",password); 

    // json Object will get the value from SOAP Adapter Service
    JSONObject obj = soapAdapterService(maps);

    /** Question here, how to add to POJO.. I have code here but not work, null values**/
        // set to Object Pojo Employee
    Employee emp = new Employee();
    emp.setUserId(String.valueOf(obj.get("userId")));
    emp.setUserStatus((String.valueOf(obj.get("userStatus")));

    // when I logging its show Empty.
    logger.info("User ID from service : " + emp.getUserId());
    logger.info("Status Id from service : " + emp.getUserStatus());


    return obj;
}

2。)Pojo Class - Employee

import java.io.Serializable;

@SuppressWarnings("serial")
public class Employee implements Serializable{
private String userid;
private String userStatus;

public String getUserid() {
        return userid;
    }

    public void setUserid(String userid) {
        this.userid= userid;
    }

    public String getUserStatus() {
        return userStatus;
    }

    public void setUserStaus(String userStatus) {
        this.userStatus= userStatus;
    }
}

当我使用Swagger - MobileFirst Console restful测试进行测试时,它会返回JsonObject并成功返回Body以及来自服务的数据。

但是当我检查日志信息(message.log) - 服务器日志时,状态为空。

来自服务的用户ID:null 来自服务的状态ID:null

似乎是它的JSON Java IBM API,它有像Jackson API这样的ObjectMapper来将JsonObject映射到POJO类。

  1. Swagger的结果
  2.  {
          "statusReason": "OK",
          "responseHeaders": {
            "Content-Length": "1849",
            "Content-Language": "en-US",
            "Date": "Thu, 23 Mar 2017 01:40:33 GMT",
            "X-Powered-By": "Servlet/3.0",
            "Content-Type": "text/xml; charset=utf-8"
          },
          "isSuccessful": true,
          "responseTime": 28,
          "totalTime": 33,
          "warnings": [],
          "Envelope": {
            "soapenv": "http://schemas.xmlsoap.org/soap/envelope/",
            "Body": {
              "checkEmployeeLoginResponse": {
                "a": "http://com.fndong.my/employee_Login/",
                "loginEmployeeResp": {
                  "Employee": {
                    "idmpuUserName": "fndong",
                    "Status": "A",
                    "userid": "fndong",
                    "Password": "AohIeNooBHfedOVvjcYpJANgPQ1qq73WKhHvch0VQtg@=",
                    "PwdCount": "1",
                    "rEmail": "fndong@gmail.com"
                  },
                  "sessionId": "%3F",
                  "statusCode": "0"
                }
              }
            }
          },
          "errors": [],
          "info": [],
          "statusCode": 200
        }
    

    然后我按照你的建议转换为String:

    String objUserId = (String) objectAuth.get("userid");
    

    结果仍为null,是否需要通过调用body函数&#34; loginEmployeeResp&#34;来指示json restful结果,因为数据JSon Object来自服务SOAP。

1 个答案:

答案 0 :(得分:1)

显然,您的String.valueOf(obj.get("userId"))返回null或为空,所以问题是,它的哪一部分?

您可以记录obj.get("userId")并查看是否为空,在这种情况下,回复不包含您的预期。

但我怀疑问题是String.valueOf()转换没有达到预期效果。看起来MobileFirst中的JSONObjectcom.ibm.json.java.JSONObject,当我在上搜索时,example I found只会转换为String

emp.setUserId((String) obj.get("userId"));

编辑:现在您已添加了Swagger结果,我说您的obj.get("userId")可能正在返回null本身。你检查过了吗?

首先,&#34; userId&#34;不是&#34;用户ID&#34;。资本化很重要。

但更重要的是,&#34; userid&#34;嵌套在JSON的深处,所以我不认为从顶级JSONObject获取它是可行的。我认为您必须做以下事情:

JSONObject envelope = (JSONObject) obj.get("Envelope");
JSONObject body = (JSONObject) envelope.get("Body");
JSONObject response = (JSONObject) body.get("checkEmployeeLoginResponse");
JSONObject resp = (JSONObject) response.get("loginEmployeeResp");
JSONObject employee = (JSONObject) resp.get("Employee");
emp.setUserId((String) employee.get("userid"));
emp.setUserStatus((String) employee.get("status"));

(遗憾的是,对于那个特定的IBM JSON4J,我认为没有办法将JSON更自动地解组成Java对象。)