Gson创建Json串,外层是一个对象,并保存到Sdcard

    Gson gson = new Gson();

        weather w = new weather();
        w.setError(0);
        w.setStatus("success");
        w.setDate("2014-05-10");

        ArrayList<results> resultslist = new ArrayList<results>();

        results results = w.new results();
        results.setCurrentCity("南京");
        ArrayList<currentCity> list = new ArrayList<currentCity>();
        for (int i = 0; i < 2; i++) {
            currentCity city = results.new currentCity();
            city.setDate("周六(今天, 实时:19℃");
            city.setDayPictureUrl("http://");
            city.setNightPictureUrl("http://");
            city.setWeather("大雨");
            city.setWind("东南风5-6级");
            city.setTemperature("18℃");
            list.add(city);
        }
        results.setCurrentCity(list);

        resultslist.add(results);
        w.setResults(resultslist);

        String json = gson.toJson(w);

        System.out.println(json);

        try {
            FileOutputStream fo = new FileOutputStream(Environment
                    .getExternalStorageDirectory() + "/Json.txt");

            fo.write(json.getBytes());
            fo.flush();
            Toast.makeText(MainActivity.this, "复制完成", 0).show();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(MainActivity.this, "复制失败", 0).show();
        }
    }
});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用Gson库来解析JSON字符为Java对象。首先,你需要导入Gson库到你的项目中。然后,可以按照以下步骤使用Gson来获取JSON字符对象: 1. 创建一个包含JSON数据的字符。 2. 创建一个Gson对象。 3. 使用fromJson()方法将JSON字符解析为相应的Java对象。 下面是一个示例代码,演示了如何使用Gson获取JSON字符对象: ```java import com.google.gson.Gson; public class Main { public static void main(String[] args) { // 创建包含JSON数据的字符 String json = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}"; // 创建Gson对象 Gson gson = new Gson(); // 使用fromJson()方法将JSON字符解析为Java对象 Person person = gson.fromJson(json, Person.class); // 打印解析后的对象 System.out.println("Name: " + person.getName()); System.out.println("Age: " + person.getAge()); System.out.println("City: " + person.getCity()); } // 定义一个Person类,用于映射JSON数据 static class Person { private String name; private int age; private String city; public String getName() { return name; } public int getAge() { return age; } public String getCity() { return city; } } } ``` 在上述示例中,我们首先创建一个包含JSON数据的字符,然后创建了一个Gson对象。接下来,我们使用fromJson()方法将JSON字符解析为Person对象。最后,我们打印了解析后的对象的属性值。 请确保在代码中修改Person类来适配你的JSON数据结构。希望这个示例可以帮助到你!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值