0

私はJavaコードを持っています:

URL oracle = new URL("https://x.x.x.x.x.x.-001");
System.out.println(oracle.openStream());
BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));

String inputLine;
while ((inputLine = in.readLine()) != null)
        System.out.println(inputLine);

接続を開き、その内容を印刷しています。内容は確かにJsonです。出力は次のようになります。

{
  "merchantId": "guest",
  "txnId": "guest-1349269250-001",
}

これをjsonの単純なjarで解析したいと思います。コードループを次のように変更しました。

JSONObject obj = new JSONObject();
while ((inputLine = in.readLine()) != null)
        obj.put("Result",inputLine);

しかし、それは機能していないようです。私が得ている出力は次のとおりです。

{"Result":"}"}
4

4 に答える 4

3

JSONParser#Parse()メソッドまたはメソッドを使用する必要がありますJSONValue#parse()

URL oracle = new URL("https://x.x.x.x.x.x.-001");
System.out.println(oracle.openStream());
Reader in = new InputStreamReader(oracle.openStream());

Object json = JSONValue.parse(in);
于 2012-10-03T12:47:54.327 に答える
2

JSON 文字列を解析する方法に関するドキュメントに従っていますか?

見た目では、文字列全体を取得して a を呼び出す必要がありますが、コードは JSON の各行で a (の親クラス) をJSONParse#parse()埋めています。実際には、反復ごとに同じキーで呼び出しているため、最後の行だけが保存されます。HashMapJSONObjectput()"Result"

于 2012-10-03T12:36:28.987 に答える
1

最初に内容全体を String 変数に読み取り、それを json に解析する必要があります。""(ダブルクォーテーション)に注意してください。Java は\"二重引用符を使用します。お気に入り。

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class JsonSimpleExample3 {

    public static void main(String args[]) {

        JSONParser parser = new JSONParser();
        //String str = "{\"merchantId\": \"guest\",\"txnId\": \"guest-1349269250-001\",}";

        //intilize an InputStream
        InputStream is = new ByteArrayInputStream("file content".getBytes());

        //read it with BufferedReader and create string
        BufferedReader br = new BufferedReader(new InputStreamReader(is));// Instead of is, you should use oracle.openStream()
        StringBuilder sb = new StringBuilder();

        String line;
        try {
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        } 

        // parse string
        try {
            JSONObject jsonObject = (JSONObject) parser.parse(sb.toString());

            String merchantId = (String) jsonObject.get("merchantId");
            System.out.println(merchantId);
            String txnId = (String) jsonObject.get("txnId");
            System.out.println(txnId);

        } catch (ParseException e) {

            e.printStackTrace();
        }
    }
}
于 2012-10-03T12:35:30.120 に答える