getting a JSON-response from API and map it with POJO-class using Mule

时间:2018-12-19 11:28:03

标签: java json mule

I would have to get a JSONArray from URL and convert the received data to a .csv -file. I'm rather new with Java and Mule. We are using Community Edition of the Mule, so the transform message -component isn't an option here.

I have created a POJO-class "JsonData" with all the getters and setters and I understood that using that POJO-class as a return class of the JSON-to-Object -transformer in Mule would match the JSON-property names to the ones in that POJO-class.

Here is my JSON data:

[
{
    "accountId": "064418ca1d292a5112e9804af4dc66df5b90203c",
    "iban": "FI2350009421535899",
    "bic": "OKOYFIHH",
    "accountName": "KÄYTTÖTILI",
    "balance": 0,
    "amountAvailable": 0,
    "currency": "EUR"
},
{
    "accountId": "07618ad83d7c5d5f2db8908d33b6a9272c5e8d96",
    "iban": "FI7858400761900714",
    "bic": "OKOYFIHH",
    "accountName": "KASVUTUOTTO",
    "balance": 3137.57,
    "amountAvailable": 3137.57,
    "currency": "EUR"
}
]

And here is my POJO-class generated by the jsonschema2pojo.org -tool:

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"accountId",
"iban",
"bic",
"accountName",
"balance",
"amountAvailable",
"currency"
})

public class JsonData {


@JsonProperty("accountId")
private String accountId;
@JsonProperty("iban")
private String iban;
@JsonProperty("bic")
private String bic;
@JsonProperty("accountName")
private String accountName;
@JsonProperty("balance")
private Double balance;
@JsonProperty("amountAvailable")
private Double amountAvailable;
@JsonProperty("currency")
private String currency;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();

@JsonProperty("accountId")
public String getAccountId() {
return accountId;
}

@JsonProperty("accountId")
public void setAccountId(String accountId) {
this.accountId = accountId;
}

@JsonProperty("iban")
public String getIban() {
return iban;
}

@JsonProperty("iban")
public void setIban(String iban) {
this.iban = iban;
}

@JsonProperty("bic")
public String getBic() {
return bic;
}

@JsonProperty("bic")
public void setBic(String bic) {
this.bic = bic;
}

@JsonProperty("accountName")
public String getAccountName() {
return accountName;
}

@JsonProperty("accountName")
public void setAccountName(String accountName) {
this.accountName = accountName;
}

@JsonProperty("balance")
public Double getBalance() {
return balance;
}

@JsonProperty("balance")
public void setBalance(Double balance) {
this.balance = balance;
}

@JsonProperty("amountAvailable")
public Double getAmountAvailable() {
return amountAvailable;
}

@JsonProperty("amountAvailable")
public void setAmountAvailable(Double amountAvailable) {
this.amountAvailable = amountAvailable;
}

@JsonProperty("currency")
public String getCurrency() {
return currency;
}

@JsonProperty("currency")
public void setCurrency(String currency) {
this.currency = currency;
}

@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}

@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}

I also have a Mule flow with GET-request, Json-To-Object -transformer, Object-To-String -transformer, logger-component and File-endpoint which writes the log or the payload to a new text file. The problem is that when I run the Mule flow, the payload isn't the one it should be... below is my Mule Flow:

<?xml version="1.0" encoding="UTF-8"?>

<mule xmlns:file="http://www.mulesoft.org/schema/mule/file" 
xmlns:json="http://www.mulesoft.org/schema/mule/json" 
xmlns:http="http://www.mulesoft.org/schema/mule/http" 
xmlns="http://www.mulesoft.org/schema/mule/core" 
xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
xmlns:spring="http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core 
http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/http 
http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/json 
http://www.mulesoft.org/schema/mule/json/current/mule-json.xsd
http://www.mulesoft.org/schema/mule/file 
http://www.mulesoft.org/schema/mule/file/current/mule-file.xsd">
<http:request-config name="HTTP_Request_Configuration" protocol="HTTPS" 
host="sandbox.apis.op-palvelut.fi" port="443" doc:name="HTTP Request 
Configuration"/>
<file:connector name="CreateFile" autoDelete="true" streaming="true" 
validateConnections="true" doc:name="File"/>
<file:endpoint path="${juuri.csv}" name="CreateCSV" responseTimeout="10000" 
doc:name="File"/>
<file:endpoint path="${juuri.log}" name="CreateLog" responseTimeout="10000" 
doc:name="File"/>
<flow name="myynnittonovaFlow">
    <poll doc:name="Poll">
        <fixed-frequency-scheduler frequency="5" timeUnit="SECONDS"/>
        <logger message="Started....." level="INFO" doc:name="Logger"/>
    </poll>
    <http:request config-ref="HTTP_Request_Configuration" path="v1/accounts" 
method="GET" doc:name="HTTP">
        <http:request-builder>
            <http:header headerName="x-authorization" value="${auth}"/>
            <http:header headerName="x-api-key" value="${api_key}"/>
        </http:request-builder>
    </http:request>
    <json:json-to-object-transformer 
returnClass="json.csv.testing.JsonData[]" doc:name="JSON to Object"/>
    <object-to-string-transformer doc:name="Object to String"/>
    <logger message="#[payload]" level="INFO" doc:name="Logger"/>
    <file:outbound-endpoint outputPattern="log.txt" connector- 
ref="CreateFile" ref="CreateLog"  responseTimeout="10000" 
doc:name="CreateLog"/>
  </flow>
</mule>

And the payload I am getting from that is:

{json.csv.testing.JsonData@22fddfa0,json.csv.testing.JsonData@34ff4054}

So am I missing something here or what could be the issue? I hope that I explained this correctly...

UPDATE:

I modified my POJO-class by adding a toString() and I was able to get the actual payloads now. My second challenge is to convert that payload to CSV using a custom method I have made.

Here is my modified POJO-class:

public class JsonData {


@JsonProperty("accountId")
private String accountId;
@JsonProperty("iban")
private String iban;
@JsonProperty("bic")
private String bic;
@JsonProperty("accountName")
private String accountName;
@JsonProperty("balance")
private Double balance;
@JsonProperty("amountAvailable")
private Double amountAvailable;
@JsonProperty("currency")
private String currency;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, 
Object>();

@JsonProperty("accountId")
public String getAccountId() {
return accountId;
}

@JsonProperty("accountId")
public void setAccountId(String accountId) {
this.accountId = accountId;
}

@JsonProperty("iban")
public String getIban() {
return iban;
}

@JsonProperty("iban")
public void setIban(String iban) {
this.iban = iban;
}

@JsonProperty("bic")
public String getBic() {
return bic;
}

@JsonProperty("bic")
public void setBic(String bic) {
this.bic = bic;
}

@JsonProperty("accountName")
public String getAccountName() {
return accountName;
}

@JsonProperty("accountName")
public void setAccountName(String accountName) {
this.accountName = accountName;
}

@JsonProperty("balance")
public Double getBalance() {
return balance;
}

@JsonProperty("balance")
public void setBalance(Double balance) {
this.balance = balance;
}

@JsonProperty("amountAvailable")
public Double getAmountAvailable() {
return amountAvailable;
}

@JsonProperty("amountAvailable")
public void setAmountAvailable(Double amountAvailable) {
this.amountAvailable = amountAvailable;
}

@JsonProperty("currency")
public String getCurrency() {
return currency;
}

@JsonProperty("currency")
public void setCurrency(String currency) {
this.currency = currency;
}

@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}

@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}

@Override
public String toString() {

  return "accountId: " +  getAccountId() + " iban: " + getIban() + " bic: " 
+ getBic() + " accountName: " + getAccountName() + " balance: " + 
getBalance() 
+ " amountAvailable: " + getAmountAvailable() + " currency: " + 
getCurrency() + "\r\n"; 
}
}

And here is the class which should do the conversion to CSV....

public class DataToCSV {
public static final String HEADER = 
"CODE;IBAN;BIC;NAME;BALANCE;AMOUNTAVAILABLE;CURRENCY";

public static String doCSV(Vector<JsonData> json) throws Exception {
    String str = new String();
    Map<String, String> values = new HashMap<String, String>();
    Gson gson = new Gson();
    JsonData[] data = gson.fromJson(json.toString(), JsonData[].class);

    for (int i = 0; i < data.length; i++) {
        try {
       values.clear();
       values.put("CODE", data[i].getAccountId());
       values.put("IBAN", data[i].getIban());
       values.put("BIC", data[i].getBic());
       values.put("NAME", data[i].getAccountName());
       values.put("BALANCE", Double.toString(data[i].getBalance()));   
values.put("AMOUNTAVAILABLE",Double.toString(data[i].getAmountAvailable()));
       values.put("CURRENCY", data[i].getCurrency());
       str=str.concat(NovaUtils.doNovaLine(values,HEADER.split(";")));

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    if (str != null && !str.isEmpty()) {
        str = HEADER + "\r\n" + str;
    }

    return str;
}


}

So I have couple of questions actually here; One is that does the doCsv() look ok and if I want to test that out, what are the parameters to assign for the method?

1 个答案:

答案 0 :(得分:0)

看起来它确实在按照您的要求进行操作。由于您的有效负载具有两个json对象,因此您将获得两个JsonData对象的数组。

如果您想记录实际的有效负载,请尝试以下操作:

<json:json-to-object-transformer returnClass="JsonData" doc:name="JSON to Object"/>
<foreach collection="#[payload]" doc:name="For Each">
    <object-to-string-transformer doc:name="Object to String"/>
    <logger message="#[payload]" level="INFO" doc:name="Logger"/>
</foreach>

您的POJO中可能需要一个toString()。

更新: 我会推荐您使用Converting JSON to XLS/CSV in Java