簡體   English   中英

Jayway JsonPath讀取String Java

[英]Jayway JsonPath read String Java

我收到一個JSON對象數組,其中一部分如下:

[{"Team":"LTD","Amount":10000.0,"Success":true},
 {"Team":"XYZ","Amount":50000.0,"Success":false}]

我想強制讀取所有字段作為字符串,以便進一步處理容易和統一。 因此, Amount必須讀取為10000.0而不是1.0E5

以下是我使用的代碼段:

String input=IOUtils.toString(inputStream);
String[] fields="Amount|Success".split("\\|");
ReadContext inputParsed =JsonPath.parse(input);
List<JSONArray> resultList=Arrays.stream(fields)
                          .map(x -> inputParsed.read("$[*]."+x,JSONArray.class))
                          .collect(Collectors.toList());
//Further code to process resultList

當我從resultList打印Amount的值和類型時,它們分別顯示為1.0E5String 在解析和讀取之間,從DoubleString的轉換似乎以意想不到的方式發生。

在這里讀了一篇類似的文章,它解決了一些不同的問題。

將在運行時提供要提取的inputStreamfields 因此,使用POJO和其他需要定義Class的方法將不起作用。

 1. You should download **org.json.jar**  this is used to convert json to what you need(String,int,etc), 
 2. Change your json format like below i mentioned

JSON:

{  
   "data":[  
      {  
         "Team":"LTD",
         "Amount":10000.0,
         "Success":true
      },
      {  
         "Team":"XYZ",
         "Amount":50000.0,
         "Success":false
      }
   ]
}

public static void main(String[] arg) throws JSONException {
        String arr = "{  \n"
                + "   \"data\":[  \n"
                + "      {  \n"
                + "         \"Team\":\"LTD\",\n"
                + "         \"Amount\":10000.0,\n"
                + "         \"Success\":true\n"
                + "      },\n"
                + "      {  \n"
                + "         \"Team\":\"XYZ\",\n"
                + "         \"Amount\":50000.0,\n"
                + "         \"Success\":false\n"
                + "      }\n"
                + "   ]\n"
                + "}";

        JSONObject obj = new JSONObject(arr);
        JSONArray data = obj.getJSONArray("data");
        int n = data.length();
        for (int i = 0; i < n; ++i) {
            final JSONObject dt = data.getJSONObject(i);
            System.out.println(dt.getString("Team"));
            System.out.println(dt.getString("Amount"));
            System.out.println(dt.getBoolean("Success"));
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM