Gson到Plain旧Java对象(PO​​JO)

时间:2014-09-24 14:10:27

标签: java json pojo

我已经阅读了GSon用户指南,并在这里查看了一些问题,但我真的很难理解为什么我在尝试使用GSon制作java对象时遇到错误

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

我确信我误解了一些简单的事情并非常感谢指导。

这是它试图解析的googlemaps网址,我正在接收它,因为我可以使用readfromurl方法将其删除。

http://maps.googleapis.com/maps/api/directions/json?origin=51.5033630,-0.1276250&destination=51.5042178,23

编辑:这是调用readsFromUrl(urlBuilder())时的输出;

  

09-24 19:57:03.879:I / System.out(4068):   { “地位”: “OK”, “路线”:[{ “waypoint_order,其中”:   [], “摘要”: “A2”, “界限”:{ “西南”:{ “LNG”: - 0.1262498, “LAT”:50.91870669999999}   “东北”:{ “LNG”:23.0020594, “LAT”:52.4304362}}, “腿”:[{ “持续时间”:{ “值”:63803, “文本”:“17   小时43分钟“},”距离“:{”值“:1825694,”文字“:”1,826   公里 “},” END_LOCATION “:{” LNG “:23.0020594,” LAT “:51.50389209999999},” START_ADDRESS “:” 70   伦敦白厅

     

SW1A 2AS,UK“,”end_address“:”Orzechów-Kolonia 2,21-109   Orzechów,科洛尼亚,   波兰 “ ”START_LOCATION“:{ ”LNG“: - 0.1262498, ”LAT“:51.5034032}, ”via_waypoint“:[], ”步骤“:[{ ”html_instructions“:” 头   北&LT; / B个在白厅/白厅/ A3212&lt; / b&gt;往   Horse Guards Ave&lt; / b&gt;“,”duration“:{”value“:17,”text“:”1   分 “},” 距离 “:{” 值 “:157,” 文本 “:” 0.2   千米 “},” END_LOCATION “:{” LNG “: - 0.1265332,” LAT “:51.50479920000001},” 折线 “:{” 点 “:” ggjyH tW]@cADYD[DUBWFy@PWD"},"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]Ei@IgAAQAOAMAK?OAK?M?M?K?I?I@I?M@S @ wEPeBBY “},” START_LOCATION “:{” LNG “: - 0.1265332,” LAT “:51.50479920000001},” 演习 “:” 转右 “ ”TRAVEL_MODE“: ”驾驶“},{ ”html_instructions“:” 打开   右&LT; / B个到维多利亚   堤/ A3211&LT; / B&gt; “中, ”时间“:{ ”值“:49, ”文本“:” 1   分 “},” 距离 “:{” 值 “:389,” 文本 “:” 0.4   千米 “},” END_LOCATION “:{” LNG “: - 0.1239744,” LAT “:51.5011942},” 折线 “:{” 点 “:” aojyHp WxH~Ab@H恩@〜@频率@ b @ B1中@ @ “},” START_LOCATION “:{” LNG “: - 0.1231268,” LAT “:51.50464890000001},” 演习 “:” 转右 “ ”TRAVEL_MODE“: ”驾驶“},{ ”html_instructions“:” 打开   左&LT; / B个到威斯敏斯特桥路/ A302&lt; / b&gt;离开收费区&lt; / div&gt;进入收费站   区&LT; / DIV&gt; “中, ”时间“:{ ”值“:62, ”文本“:” 1   分 “},” 距离 “:{” 值 “:507,” 文本 “:” 0.5   千米 “},” END_LOCATION “:{” LNG “: - 0.1170572,” LAT? “:51.50053550000001},” 折线 “:{” 点 “:” myiyHxeW @ ABABCB DADCBABCBC @ CBEBI沃顿ê@ g ^ @ GBW @@ } @@ @ QA Q因子@ DkFFkF KFuAFgAEYC [艾@?] @ @@克的iA _ @ö@ú@ Q因子@ KBMBGBGP [FM “},” START_LOCATION “:{” LNG “: - 0.1239744,”????LAT “:51.5011942},” 机动 “:” 转左 “ ”TRAVEL_MODE“: ”DRIVING“},{ ”html_instructions“:” 轻微   左&LT; / B个留在威斯敏斯特桥路/ A302&lt; / b&gt;离开收费站   区&LT; / DIV&gt; “中, ”时间“:{ ”值“:4 ”文本“:” 1   分 “},” 距离 “:{” 值 “:26,” 文本 “:” 26   米 “},” END_LOCATION “:{” LNG? “: - 0.1167459,” LAT “:51.5004276},” 折线 “:{” 点 “:” kuiyHrzUFIBEBG @ģ@ģ@克间 “},” START_LOCATION“:{ “液化天然气”: - 0.1170572, “LAT”:51.50053550000001}, “演习”: “关轻微左”, “TRAVEL_MODE”: “驾驶”},{ “html_instructions”:“打开   左&LT; / B个留在威斯敏斯特桥   RD / A302&LT; / B&gt; “中, ”时间“:{ ”值“:4 ”文本“:” 1   分 “},” 距离 “:{” 值 “:23,” 文本 “:” 23   米 “},” END_LOCATION “:{” LNG “: - 0.1165272,” LAT “:51.5005834},” 折线 “:{” 点 “:” utiyHtxUIQIMIK “},” START_LOCATION “:{” LNG “: - 0.1167459,” LAT “:51.5004276},” 演习 “:” 转左 “ ”TRAVEL_MODE“: ”驾驶“},{ ”html_instructions“:” 轻微   右&LT; / B个留在威斯敏斯特桥   RD / A302&LT; / B&gt; “中, ”时间“:{ ”值“:10, ”文本“:” 1   分 “},” 距离 “:{” 值 “:52,” 文本 “:” 52   米 “},” END_LOCATION “:{” LNG “: - 0.1158714,”?LAT “:51.5007879},” 折线 “:{” 点 “:” suiyHhwUEa @ GUGQQc @ AE G G “},” START_LOCATION“:{ “液化天然气”: - 0.1165272, “LAT”:51.5005834}, “演习”: “关轻微右”, “TRAVEL_MODE”: “驾驶”},{ “html_instructions”:“打开   右&LT; / B个留在威斯敏斯特桥路/ A302&lt; / b&gt;继续沿威斯敏斯特大桥行驶   Rd&lt; / div&gt;输入收费   区&LT; / DIV&gt; “中, ”时间“:{ ”值“:93, ”文本“:” 2   分钟 “},” 距离 “:{” 值 “:848,” 文本 “:” 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

1 个答案:

答案 0 :(得分:0)

嘿,Java对象与json的映射是不正确的。

示例:路线有边界,腿,版权,步骤,而不是上面代码中映射的方式。