我已阅读GSon用户指南并查看了一些关于此处的问题,但我非常努力地理解为什么我在尝试使用GSon创建java对象时出现错误Gson to Plain旧Java对象(POJO)
public class TestJSON extends ActionBarActivity {
private Location start;
private String length;
private String url = "http://maps.googleapis.com/maps/api/directions/json?origin=";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_json);
// dummyprovider is provided by google to let me set a location.
start = new Location("dummyprovider");
start.setLatitude(51.5033630);
start.setLongitude(-0.1276250);
// Recieve an android warning if you run a retrieval task (such as JSON)
// in the main thread).
try {
System.out.println("printing Json");
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
toJava(readJsonFromUrl(urlBuilder()));
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.test_json, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
// I think in future I will call this function a ton of times and send it
// some locations as waypoints for it to try and get closer to the
// distances.
private String urlBuilder() {
String newUrl = url + start.getLatitude() + "," + start.getLongitude()
+ "&destination=51.5042178,23";
return newUrl;
}
// Builds the string for JSON.
private String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
// Take an input url and reads from it using the url above. We then put it
// into a JSON object.
private JSONObject readJsonFromUrl(String url) throws IOException,
JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is,
Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
private void toJava(JSONObject obj) throws Exception {
Gson gson = new Gson();
MapsRoute m = gson.fromJson(readJsonFromUrl(urlBuilder()).toString(),
MapsRoute.class);
System.out.println(m);
}
}
MapsRoute.java
public class MapsRoute {
@SerializedName("routes")
public List<String> routes;
@SerializedName("copyrights")
public String copyrights;
@SerializedName("legs")
public List<String> legs;
@SerializedName("steps")
public List<String> steps;
}
这是堆栈跟踪
09-24 19:22:47.367: W/System.err(1720): com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 27
09-24 19:22:47.367: W/System.err(1720): at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176)
09-24 19:22:47.367: W/System.err(1720): at com.google.gson.Gson.fromJson(Gson.java:803)
09-24 19:22:47.367: W/System.err(1720): at com.google.gson.Gson.fromJson(Gson.java:768)
09-24 19:22:47.367: W/System.err(1720): at com.google.gson.Gson.fromJson(Gson.java:717)
09-24 19:22:47.367: W/System.err(1720): at com.google.gson.Gson.fromJson(Gson.java:689)
09-24 19:22:47.367: W/System.err(1720): at boyle.matt.runrouter.TestJSON.toJava(TestJSON.java:119)
09-24 19:22:47.367: W/System.err(1720): at boyle.matt.runrouter.TestJSON.access$2(TestJSON.java:117)
09-24 19:22:47.371: W/System.err(1720): at boyle.matt.runrouter.TestJSON$1.run(TestJSON.java:47)
09-24 19:22:47.371: W/System.err(1720): at java.lang.Thread.run(Thread.java:856)
09-24 19:22:47.371: W/System.err(1720): Caused by: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 27
09-24 19:22:47.371: W/System.err(1720): at com.google.gson.stream.JsonReader.nextString(JsonReader.java:821)
09-24 19:22:47.371: W/System.err(1720): at com.google.gson.internal.bind.TypeAdapters$13.read(TypeAdapters.java:358)
09-24 19:22:47.371: W/System.err(1720): at com.google.gson.internal.bind.TypeAdapters$13.read(TypeAdapters.java:346)
09-24 19:22:47.371: W/System.err(1720): at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:40)
09-24 19:22:47.371: W/System.err(1720): at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:81)
09-24 19:22:47.371: W/System.err(1720): at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:60)
09-24 19:22:47.371: W/System.err(1720): at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:93)
09-24 19:22:47.371: W/System.err(1720): at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:172)
09-24 19:22:47.371: W/System.err(1720): ... 8 more
我确定我误解了一些简单的东西,非常感谢您的指导。
这是它试图分析的谷歌地图网址,我成功接收它,因为我可以在我的readfromurl方法中将它系统化。
编辑:这是调用readsFromUrl当输出(urlBuilder());
09-24 19:57:03.879:I /的System.out(4068): { “状态”: “OK”, “路由”:[{ “waypoint_order,其中”: [],“摘要“:”A2“,”bounds“:{”southwest“:{”lng“: - 0.1262498,”lat“:50.91870669999999}, ”northeast“:{”lng“:23.0020594,”lat“:52.4304362}}, “腿”:[{“duration”:{“value”:63803,“text”:“17 小时43分钟”},“distance”:{“value”:1825694,“text”:“1,826 km” }, “END_LOCATION”:{ “LNG”:23.0020594, “LAT”:51.50389209999999}, “START_ADDRESS”: “70 白厅,伦敦
SW1A 2AS,英国”, “END_ADDRESS”:“Orzechów-科洛尼亚2, 21-109 Orzechów-Kolonia, Poland“,”start_location“:{”lng“: - 0.1262498,”lat“:51.5034032},”via_waypoint“:[],”steps“:[{”html_instructions“:”Head north </b> on Whitehall/Whitehall/A3212 </b>朝 Horse Guards Ave </b>“,”duration“:{”value“:17,”text“:”1 min“},distance “:{”value“:157,”text“:”0.2 km“},”end_location“:{”lng“: - 0.1265332,”lat“:51.50479920000001}”polyline“:{”points“”ggjyH
tW]@cADYD[[email protected]"},"travel_mode":"DRIVING","start_location":{"lng":-0.1262498,"lat":51.5034032}},{"html_instructions":"Turn <b>right<\/b> onto <b>Horse Guards Ave<\/b>","duration":{"value":53,"text":"1 min"},"distance":{"value":242,"text":"0.2 km"},"end_location":{"lng":-0.1231268,"lat":51.50464890000001},"polyline":{"points":"_pjyHxuWC][email protected][email protected][email protected]
@wEPeBBY“},”start_location“:{”lng“: - 0.1265332,”lat“:51.50479920000001},”机动“:”右转“,”travel_mode“:”DRIVING“},{”html_instructions“转 右</b>驶入维多利亚 路堤/ A3211 </b>“,”duration“:{”value“:49,”text“:”1距离“:{”value“:389,”text“:”0.4 km“},”end_location“:{”lng“: - 0.1239744,”lat“:51.5011942},”polyline“: {“points”:“aojyHp[email protected]
En @〜@F @?b @ Bl @@”},“start_location”:{“lng”: - 0.1231268,“lat”:51.50464890000001},“机动”:“右转“,”travel_mode“:”DRIVING“},{”html_instructions“:”转 离开</b>转入威斯敏斯特桥路/ A302 </b>离开收费区</div>进入收费区 区</,“duration”:{“value”:62,“text”:“1 min”},“distance”:{“value”:507,“text”:“0.5 km”},“end_location” “LNG”: - 0.1170572, “LAT”:51.50053550000001}, “折线”:{ “点”:“myiyHxeW @ ABABCB DADCBABCBC @ CBEBIķ| E @ģ@ @@ GBW} @@ @ QA q因子@ DkFFkF???? KFuAFgAEYC @ @@克的iA _ @ö@ú@ Q因子@ KBMBGBGP [FM “},” START_LOCATION “:{” LNG “: - 0.1239744,”[艾@?]?LAT“:51。5011942},“机动”:“左转”,“travel_mode”:“驾驶”},{“html_instructions”:“稍微 离开</b>留在威斯敏斯特桥路/ A302 </b>离开收费 区域</div>“,”duration“:{”value“:4,”text“:”1 min“},”distance“:{”value“:26,”text“:”26 m“} “END_LOCATION”:{ “LNG”: - 0.1167459, “LAT”:51.5004276}, “折线”:{ “点”: “kuiyHrzUFIBEBG @ģ@ģ@克间?”}, “START_LOCATION”:{ “LNG” :-0.1170572,“lat”:51.50053550000001},“机动”:“左转轻微”,“travel_mode”:“驾驶”},{“html_instructions”:“转 左</b>留在威斯敏斯特桥“{”value“:4,”text“:” min“}米 “},” end_loca重刑 “:{” LNG “: - 0.1165272,” LAT “:51.5005834},” 折线 “:{” 点 “:” utiyHtxUIQIMIK “},” START_LOCATION “:{” LNG “: - 0.1167459,” LAT“:51.5004276} ,“机动”:“左转”,“travel_mode”:“驾驶”},{“html_instructions”:“稍微 右</b>留在威斯敏斯特桥 Rd/A302 </b>”, “:{”value“:10,”text“:”1 min“},”distance“:{”value“:52,”text“:”52 m“},”end_location“:{”lng“ :-0.1158714, “LAT”:51.5007879}, “折线”:{ “点”: “suiyHhwUEa @ GUGQQc @ AE G G?”}, “START_LOCATION”:{ “LNG”: - 0.1165272, “LAT”:51.5005834 },“maneuver”:“turn-slight-right”,“travel_mode”:“DRIVING”},{“html_instructions”:“转 右</b>留在威斯敏斯特桥路/ A302 </b>按照威斯敏斯特桥 Rd </div> Ente电话号码 区域</div>“,”duration“:{”value“:93,”text“:”2 mins“},”distance“:{”value“:848,”text“:”0.8 公里 “},” END_LOCATION “:{” LNG “: - 0.1051152,” LAT “:51.49874029999999},” 折线 “:{” 点 “:”} viyHdsU @ EBG | E @ CBEBCFGNQBMFMLYZm @ b @ö@ d @Ò@ FUDKd @ oAXe @ Vs的@〜@ ICN [DKFKDGBGJYb @ _B \ mBRiAHa @ BO @我?g | E?g @ @@ UBE] CMAOIyAAo @·K·G·EGyAAe @ EoAIwCKyCEoAAa @ GiBIc @ CQCW “},” START_LOCATION” :{ “LNG”: - 0.1158714, “LAT”:51.5007879}, “演习”: “转右”, “TRAVEL_MODE”:“DR
没有看任何东西,'预期一个字符串,但是BEGIN_OBJECT'对你来说意味着什么? – 2014-09-24 14:18:12
调试并显示从'readJsonFromUrl()'返回的'json'。这似乎不是一个有效的JSon对象。或者至少对您的解析器无效。 – Narmer 2014-09-24 14:18:22
@SotiriosDelimanolis没有什么,这就是为什么我要求帮助:)谷歌搜索建议这是因为我的字符串数据结构是错误的,但其他的例子似乎使用我的设置。 – 2014-09-24 14:21:56