简体   繁体   中英

Retrofit Android Application GET JSON from Node.js Server

I solved the problem. I was sending plain-text in the server. Changed the line to read:

response.writeHead(200, {'Content-Type': 'application/json'});

Quick question. My friend recommended looking into Retrofit rather than using my ASync task for my REST android application. I am having one small problem since I am new to the system. The server runs using Node.js to send JSON objects by means of .stringify() and so when I retrieve an object it is a String rather than a JSON, and I cannot convert it to my List of the appropriate objects. I am guessing the error is due to a cast exception because it is sending a string because I get the exception:

com.google.gson.JsonSyntaxException

Any help would be great. Here is the code I thought would be appropriate.

Android Client Code Example below:

private void requestData() {
    RestAdapter adapter = new RestAdapter.Builder().setEndpoint(ENDPOINT).build();
    UnitAPI unit_api = adapter.create(UnitAPI.class);

    unit_api.getUnits(new Callback<List<Unit>>() {

        @Override
        public void success(List<Unit> t, Response response) {
            units = t;
            updateDisplay();
        }

        @Override
        public void failure(RetrofitError error) {
            Log.d("Failure UnitGet()", error.getMessage());

        }
    });

}

Android Unit.class:

public class Unit {

private String ID;
private long bearing;
private long lat;
private long lng;
private String type;

public String getID() {
    return ID;
}
public void setID(String ID){
    this.ID = ID;
}
public long getBearing() {
    return bearing;
}
public void setBearing(long bearing){
    this.bearing = bearing;
}
public void setLat(long lat){
    this.lat = lat;
}
public long getLat(){
    return lat;
}
public void setLng(long lng){
    this.lng = lng;
}
public long getLng(){
    return lng;
}
public void setType(String type){
    this.type = type;
}
public String getType(){
    return type;
}
}

The server sends the .json file via the command:

if (method == "GET") {                                            
  response.write(JSON.stringify(unitsJSON));
}

Any thoughts on how I can convert it to a list of units from the string on the client side or a json object on the server side?

Thanks!

I solved the problem. I was sending plain-text in the server. Changed the line to read:

response.writeHead(200, {'Content-Type': 'application/json'});

I think you must add json-parser to package using npm then
in response write

res.end(JSON.stringfy('your resp0onse here'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM