2017-04-24 13 views
0
String test ="{"abc":null}"; 
JSONObject testObj = new JSONObject(test); 

abcはJSONObjectではないため、エラーが発生します。この文字列をJSONオブジェクトに変換するにはどうすればよいですか?JSON文字列をJSONに変換するnull値を持つオブジェクト

実際の実装では、 'test'という文字列があります。ファイルから読み込んでいます。エスケープシーケンスは追加されていません。

+0

これを使用すると、String test = "{\" abc \ ":null}"; –

答えて

1

文字列の連結が正しくありません。 abcはオブジェクトですか?それとも文字列abcですか?

String test = "{" + "abc" + ":null}"; 

が、上記の場合には、あなたは、単に実行する必要があります。

String test = "{abc:null}"; 

またはABCは、別の定義された文字列変数である場合は、次のように言う:あなたはそれらの必要

String abc = "awesomeText"; 
String test = "{" + abc + ":null}"; 

それともをabcからの引用 "\"を使用して引用符文字をエスケープします。このように:

String test ="{\"abc\":null}"; 
0

私はこのテストを作り、それが私のためにうまく働いた:

public static void main(String[] args) { 
    BufferedReader br; 
    try { 
     br = new BufferedReader(new FileReader("C:\\test.json")); 

     String currentLine; 
     while ((currentLine = br.readLine()) != null) { 
      JSONObject testObj = new JSONObject(currentLine); 
      System.out.println(testObj); 
     } 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
} 

test.jsonファイルの内容を再生しながら、私は多くの成功のテストを試してみました:

  1. {"abc":null}
  2. {'abc':null}
  3. {abc:null}
関連する問題