zoukankan      html  css  js  c++  java
  • JAVA_JSON

     1 package cn.kjxy.JSON;
     2 
     3 import org.json.JSONArray;
     4 import org.json.JSONException;
     5 import org.json.JSONObject;
     6 /**
     7 *json解析需要导入json-lib.jar包,安卓自带而非Java
     8     
     9 */
    10 class Student{
    11     private String name;
    12     private int age;
    13     public String getName() {
    14         return name;
    15     }
    16     public void setName(String name) {
    17         this.name = name;
    18     }
    19     public int getAge() {
    20         return age;
    21     }
    22     public void setAge(int age) {
    23         this.age = age;
    24     }
    25     @Override
    26     public String toString() {
    27         return "Student [name=" + name + ", age=" + age + "]";
    28     }
    29     
    30 }
    31 public class Demo1 {
    32     public static void main(String[] args) {
    33         try {
    34             //json数据描述学生对象
    35             //格式一 {}-->JSONObject解析
    36             String json = "{name:'张三',age:18}";
    37             JSONObject jsonObject = new JSONObject(json);
    38             Student student = new Student();
    39             student.setName(jsonObject.getString("name"));
    40             student.setAge(jsonObject.getInt("age"));
    41             System.out.println(student);
    42             ///格式二 [] -->JSONArray解析
    43             String array = "['张三','李四','王五']";
    44             JSONArray jsonArray = new JSONArray(array);
    45             for (int i = 0; i < jsonArray.length(); i++) {
    46                 System.out.println(jsonArray.getString(i));
    47                 
    48             }
    49         
    50         } catch (JSONException e) {
    51             // TODO Auto-generated catch block
    52             e.printStackTrace();
    53         }
    54     }
    55 }
  • 相关阅读:
    Loj #6307. 「雅礼国庆 2017 Day1」Clique
    bzoj 4457: 游戏任务
    Codeforces 375 D Tree and Queries
    Codeforces 837 E Vasya's Function
    [POI2008]BLO
    Codeforces 451 E Devu and Flowers
    洛谷 P4318 完全平方数
    [JSOI2016]反质数序列
    bzoj 4320: ShangHai2006 Homework
    bzoj4454 C Language Practice
  • 原文地址:https://www.cnblogs.com/fangg/p/5545196.html
Copyright © 2011-2022 走看看