1
我正在處理一個基本的JSON問題: 我使用JSON格式的字符串(從http://api.open-notify.org/iss-now.json)。 我把它傳遞到一個方法,試圖解析信息到一個名爲ISSClass的類,以便我可以讀取經度和緯度的字段。解析基本JSON對象時,如何讓GSON不返回null?
當我嘗試返回它們爲空的兩個字段。
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.Expose;
public class GetWeather
{
public String getISSInfo(String json)
{
String output="";
Gson gson=new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
ISSClass cond=new ISSClass();
cond= gson.fromJson(json, ISSClass.class);
output+="The ISS is at: "+cond.toString();
return output;
}
class ISSClass
{
public ISSClass(){}
@Expose
public String latitude;
@Expose
public String longitude;
public String toString()
{
return latitude+", "+longitude;
}
public void setLongitude(String lon)
{
longitude=lon;
}
public void setLatitude(String lat)
{
latitude=lat;
}
public String getLongitude()
{
return longitude;
}
public String getLatitude()
{
return latitude;
}
}
}
而這裏的主:
public class GsonTester
{
public static void main(String[] args) throws Exception
{
JsonReader reader=new JsonReader();
String toParse="{\"message\": \"success\", \"timestamp\": 1501887780, \"iss_position\": {\"latitude\": \"-35.5370\", \"longitude\": \"-178.7080\"}}";
GetWeather weather=new GetWeather();
System.out.println(weather.getISSInfo(toParse));
}
}
我使用@SerializedName( 「經度」),沒有運氣嘗試。 與實例化'gson'相同 Gson gson = new Gson(); 我爲gson使用gson-2.8.1.jar。
希望我失去了一些明顯的東西。
我想我失去了一些東西。感謝您的幫助,對於初學者來說很抱歉 – Alej