首页 > 解决方案 > 如何在这里实现一个 json 解析器?

问题描述

我用 json 创建了一个 post 请求,它工作得很好。但现在我想将此 json post 请求的输出插入到我的数据库中。

所以我需要创建一个 json 解析器来分隔这样的字符串:“Bestellnummer:1”、“Besteller:8195529”、“Zeit:2019-09-27 15:50:07”、“Artikelnummer:76194”、“Anzahl :1", "Preis:2.968"...(下一个 Artikelnummer 等等...)。

Bestellnummer = orderid, Besteller = customerid, Zeit = time, Artikelnummer=articleid, Anzahl = 文章数量, Preis= 价格

我试图在我的代码中做类似解析器的事情,但我从来没有做过这样的事情,不幸的是不知道如何在我的代码中使用这个解析器。

我希望你能帮助我

我的 json 输出的一个例子:

{"Bestellnummer":"1","Besteller":"8195529","Zeit":"2019-09-27 15:50:07","Artikel":[{"Artikelnummer":"76194","Anzahl":"1","Preis":"2.968"},{"Artikelnummer":"61681","Anzahl":"1","Preis":"7.147"},{"Artikelnummer":"111756","Anzahl":"1","Preis":"9.29"},{"Artikelnummer":"14227","Anzahl":"1","Preis":"0"}]}

代码:

private static String dirPath = "https://hauteuchdrum.informatik.uni-siegen.de/propra/aufgaben/ws1920/index.php";
         public ArrayList<String> Bestellung(){
            File file = new File (dirPath + "//array_complex.json");
            ArrayList <String> test = new ArrayList<String>();
            try {
                String str = "{ \"Bestellnummer\": [1,2,3,4,5] }";

                // holt alle 47550 bestellungen vom json  
                for (int i=1; i<2;i++) {
                String POST_PARAMS = "json={\"bid\":\"bid\", \"getorder\":\""+i+"\"}";
                    //System.out.println(POST_PARAMS);

                JSONObject obj1 = new JSONObject(POST_PARAMS);
                JSONArray arr=obj1.getJSONArray("Bestellnummer");
                for (int z=0; z<arr.length();z++) {
                    String post_id = arr.getJSONObject(z).getString("Bestellnummer");
                    System.out.println(post_id);
                }
                 URL obj = new URL("https://hauteuchdrum.informatik.uni-siegen.de/propra/aufgaben/ws1920/index.php");
                 HttpURLConnection postConnection = (HttpURLConnection) obj.openConnection();
                 postConnection.setRequestMethod("POST");
                 postConnection.setRequestProperty("connection", "Keep-Alive");
                 postConnection.setDoOutput(true);
                 java.io.OutputStream os = postConnection.getOutputStream();
                    os.write(POST_PARAMS.getBytes());
                    os.flush();
                    os.close();

                    int responseCode = postConnection.getResponseCode();
                    //System.out.println("POST Response Code :  " + responseCode);
                   // System.out.println("POST Response Message : " + postConnection.getResponseMessage());
                    if (responseCode == HttpURLConnection.HTTP_OK) { //success
                        BufferedReader in = new BufferedReader(new InputStreamReader(postConnection.getInputStream()));
                        String inputLine;
                        StringBuffer response = new StringBuffer();
                        while ((inputLine = in.readLine()) != null) {
                            response.append(inputLine);
                        } 
                        in.close();
                        // print result
                      //  System.out.println(response.toString());
                        test.add(response.toString());
                     //   java.util.Iterator<String> it = test.iterator();
                     // while (it.hasNext()) {
                       //   System.out.println(it.next());
                    //    }

                    }
        }
            }
            catch (Exception e) {
                System.out.println();
            }
            return test;
        }

标签: javajsonparsing

解决方案


如果您想要将 HTTP 响应字符串插入数据库,我强烈建议您将字符串反序列化为 POJO,如下所示:

声明 2 个类 -MyResponseArtikel. Artikel用于将 JOSN 对象的内容存储在 JSON 数组中,我List<Artikel>用于 JSON 数组。顺便说一句,我还使用@JsonProperty(在 Jackson 中提供)将带有大写的 JSON 键映射到带有小写的变量。

class MyResponse {
    @JsonProperty(value="Bestellnummer")
    private String bestellnummer;
    @JsonProperty(value="Besteller")
    private String besteller;
    @JsonProperty(value="Zeit")
    private String zeit;
    @JsonProperty(value="Artikel")
    private List<Artikel> artikel;

    //general getters and setters
}

class Artikel {
    @JsonProperty(value="Artikelnummer")
    private String artikelnummer;
    @JsonProperty(value="Anzahl")
    private String anzahl;
    @JsonProperty(value="Preis")
    private String preis;

    //general getters and setters
}

现在,您可以使用 Jackson(最流行的 JSON 库之一)反序列化对我们的 POJO 的 HTTP 响应。您可以轻松地操纵这些 POJO 进行 DB 操作。

ObjectMapper mapper = new ObjectMapper();
MyResponse myResponse = mapper.readValue(response.toString(), MyResponse.class);
myResponse.getArtikel().forEach(System.out::println);

控制台输出

Artikel [artikelnummer=76194, anzahl=1, preis=2.968]
Artikel [artikelnummer=61681, anzahl=1, preis=7.147]
Artikel [artikelnummer=111756, anzahl=1, preis=9.29]
Artikel [artikelnummer=14227, anzahl= 1、preis=0]


推荐阅读