7

DB に保存されている JSON をフェッチし (JSON は DB に文字列として保存されます)、コントローラーのモデル オブジェクトに追加します。

@RequestMapping( method = RequestMethod.GET, value = "/all" )
public void getJson(HttpServletRequest httpServletRequest, Model model){

    String json = serviceDao.getResponseJson(); 
    System.out.println(json); //Output: {"Response":[{"Id":"1","Name":"GAD"},{"Id":"2","Name":"GBD"}],"Status":"Success"}
    model.addAttribute("result",json);
}

しかし、ブラウザからサービスを呼び出すと、応答にエスケープ文字が追加されます。

http://localhost:8080/MyApplication/all.json

{"result":"{\"Response\":[{\"Id\":\"1\",\"Name\":\"GAD\"},{\"Id\":\"2 \",\"名前\":\"GBD\"}],\"ステータス\":\"成功\"}"}

エスケープ文字を使用せずに Web サービスで JSON オブジェクトをクライアントに送信する方法を教えてください。

4

4 に答える 4

4

文字列をモデルに追加する代わりに、JSON を直接返す

@RequestMapping(value="/all")
public @ResponseBody String getJson(){
   //Logic
    return json; 
}
于 2015-10-14T05:50:54.250 に答える
0

それは間違いなく動作します。

 String str = "result':'\'\'Respon'";
 String result = str.replaceAll("\\\'", ""); 
 Log.e("Result",result);
于 2015-10-14T05:49:06.693 に答える
0

Spring を使用している場合は@ResponseBody、String の代わりにクラス オブジェクトを使用して直接返すことができます。

このリンクにある例を参照できます。

また、maven の依存関係を含めることを忘れないでください。

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.12</version>
</dependency>
于 2015-10-14T05:49:55.487 に答える
0

あなたはreplaceAllを使用することができます:

String json = serviceDao.getResponseJson();

if (json != null && !json.isEmpty()) {
    model.addAttribute("result", json.replaceAll("\\\\", ""));
}
于 2015-10-14T05:46:33.513 に答える