将Rest响应转换为CSV

时间:2018-10-02 12:44:38

标签: java json rest csv jackson

所以我正在通过Rest从服务器上获取文件,为此我使用了RestAssured。我的目标是将此JSON输出到CSV文件。

我的问题是,我从服务器获得的响应至少为500行JSON属性和值,我觉得为此创建POJO并将值分配给变量不仅麻烦,而且效率低下,因为我只将4个文件输出到CSV。

我的主要问题是,进行转换的最佳方法是什么,我应该放心地为我需要的4个变量创建一个POJO,然后逐一分配JSON,如文档所述:

// EXAMPLE FROM DOCUMENTATION
String json = get("/lotto").asString();
// Now use JsonPath to get data out of the JSON body
int lottoId = with(json).getInt("lotto.lottoId);
List winnerIds = with(json).get("lotto.winners.winnerId");

有了这个POJO,我可能可以使用Jackson左右转换为CSV,或者还有更好的选择吗? 另外,我应该将服务器响应转换为什么以实现更好的转换? InputStream,字符串,对象映射?

InputStream result =
    given().
        body(bodyMap).
        contentType("application/json\r\n").
    when().
        post("http://localhost:9090/api/foo").
    body()
        .asInputStream(); // ?
//      .asString(); ?
//      .jsonPath().getMap("$"); ?

请求中的JSON:

{
  "content" : [ {
    "name" : "Order X",
    "business" : {
      "cod" : 1
      "name" : "Foo Bar",
      "_links" : {
        "self" : {
          "href" : "http://localhost:9090/api/link"
        }
      }
    },
    "totalValue" : 866.55000,
    "finalDate" : "2018-10-02T11:03:34.777Z",
    "state" : "OPEN",
    "clientsNumber" : 1,
    "itenQuantity" : 13,
    "initialDate" : "2018-10-02T11:03:34.777Z",
    "origin" : {
      "type" : "x",
      "_links" : {
        "self" : {
          "href" : "http://localhost:9090/api/link"
        }
      }
    },
    "itens" : [ {
      "quantity" : 1.00000,
      "subtotal" : 11.99000,
      "product" : {
        "enabled" : true,
        "name" : "Some Product",
        "cod" : "1",
        "desc" : "Healthy",
        "price" : 11.99000,
        "costPrice" : 6.00000,
        "imagemFile" : null,
        "internUse" : false,
        "_links" : {
          "self" : {
            "href" : "http://localhost:9090/api/link"
          }
        }
      },
      "unitPrice" : 11.99000,
      "sale" : {
        "name" : "Sale X",
        "_links" : {
          "self" : {
            "href" : "http://localhost:9090/api/link"
          }
        }
      },
      "state" : "WAITING",
      "dateTime" : "2018-10-02T11:03:34.777Z",
      "observation" : null,
      "_links" : {
        "self" : {
          "href" : "http://localhost:9090/api/link"
        }
      }
    },
   {...} repeats for every product in the order

预期的CSV输出:

order_n,business_cod,item_cod,item_quant
4214,5215,6126,2
4214,5215,244,5

0 个答案:

没有答案