2017-03-01 3 views
0

に私はJavaでのRESTful Webサービスに取り組んでいると私は有効なJSONを返すこのメソッドを持つJSONオブジェクトを送り返す:は、応答(ない文字列バージョン)

@GET 
@Produces(MediaType.APPLICATION_JSON) 
public Response getJSON() 
{ 
    String json = "{\"data\": \"This is my data\"}"; 
    return Response.ok(json).build(); 
} 

私が午前問題がありますJSONが文字列形式であることを示します。 オブジェクトフォームに戻すにはどうすればよいですか?応答データは、ここではJavaScript側から自分のWebサービス呼び出し

//Use of the promise to get the response 
let promise = this.responseGet() 
promise.then(
    function(response) { //<--- the param response is a string and not an object :(
     console.log("Success!", response); 
    }, function(error) { 
     console.error("Failed!", error); 
    } 
); 

//Response method  
responseGet() 
{ 
    return new Promise(function(resolve, reject) { 

     let req = new XMLHttpRequest(); 
     req.open('GET', 'http://localhost:8080/TestWebService/services/test'); 

     req.onload = function() { 
      if (req.status == 200) { 
      resolve(req.response); 
      } 
      else { 
      reject(Error(req.statusText)); 
      } 
     }; 

     req.onerror = function() { 
      reject(Error("There was some error.....")); 
     }; 

     req.send(); 
    }); 
} 
+0

おそらく[JavaでJSONとしてのHTTPResponse]と複製されています(http://stackoverflow.com/questions/17191412/httpresponse-as-json-in-java) –

答えて

0

JavaScriptでJSON.parse()を使用するだけです。

promise.then(
function(response) { 
    response = JSON.parse(response); 
    console.log("Success!", response); 
} 

あなたのresponseGet関数は、あなたがバックエンドから送信したものであっても、解析されたオブジェクトを返しません。

+0

JSON Stringを返すのは、バックエンドから日付を返すための通常の/適切な方法ですか?いつもJSON.parse()を使用する必要はありませんか? – NoodleBowl

+0

文字列は返されませんが、レスポンスは常に1つ前に解析されています。それについての詳細はこちらhttp://stackoverflow.com/questions/1973140/parsing-json-from-xmlhttprequest-responsejson最初の回答 – baao

+1

ありがとうございました。 – NoodleBowl

1

が念のために、文字列

として戻って来ているので、現在の状態では、私は、とすぐに私の応答を返すようにそれに取り組むことができませんResponseBuilder 2番目のパラメータでMediaTypeを渡して試してみてください:あなたはこれで注釈を付ける場合

@GET 
@Produces(MediaType.APPLICATION_JSON) 
public Response getJSON() 
{ 
    String json = "{\"data\": \"This is my data\"}"; 
    return Response.ok(json, MediaType.APPLICATION_JSON).build(); 
} 
+0

これは機能しませんでした:( – NoodleBowl

0
@GET 
@Produces ("application/json") 

それが動作するはずです。

関連する問題