1. 程式人生 > 其它 >2021-01-15

2021-01-15

技術標籤:java

XML和JSON

1 XML知識點

1.1 解析XML

public class Demo1 {
    public static void main(String[] args) throws IOException, DocumentException {
        FileInputStream fis=new FileInputStream("e://Demo.xml");
        SAXReader sr=new SAXReader();
        Document doc = sr.read(fis);
        Element root = doc.getRootElement();
        //System.out.println(root.getName());
        Element book = root.element("book");
        Element name=book.element("name");
        System.out.println(name.getText());
        /*List<Element> es=root.elements();
        for(int i=0;i<es.size();i++){
            Element book = es.get(i);
            System.out.println(book.elementText("id"));
            System.out.println(book.elementText("name"));
            System.out.println(book.elementText("info"));
            System.out.println("----------------");
        }*/
        fis.close();
    }

}

1.2 解析網址的XML

public class Demo2 {
    public static void main(String[] args) throws IOException, DocumentException {
        String phone="17845109827";
        URL url=new URL("http://apis.juhe.cn/mobile/get? phone="+phone+"&dtype=xml&key=9f3923e8f87f1ea50ed4ec8c39cc9253");
        URLConnection conn = url.openConnection();
        InputStream is = conn.getInputStream();
        SAXReader sr=new SAXReader();
        Document doc = sr.read(is);
        Element root = doc.getRootElement();
        String code=root.elementText("resultcode");
        if("200".equals(code)){
            Element result = root.element("result");
            String provice = result.elementText("province");
            String city = result.elementText("city");
            if(provice.equals(city)){
                System.out.println("手機號碼的歸屬地:"+provice);
            }
            else{
                System.out.println("手機號碼的歸屬地:"+provice+" "+city);
            }
        }else{
            System.out.println("請輸入正確的電話號碼");
        }

    }
}

1.3 XPATH解析 (有條件解析)

public class Demo3 {
    public static void main(String[] args) throws IOException, DocumentException {
        FileInputStream fis=new FileInputStream("e://Demo.xml");
        SAXReader sr=new SAXReader();
        Document doc = sr.read(fis);
        /*List<Node> names=doc.selectNodes("//book[@id='1001']//name");
        for(int i=0;i<names.size();i++){
            System.out.println(names.get(i).getName());
            System.out.println(names.get(i).getText());
        }*/
        Node node = doc.selectSingleNode("//book[@id='1001']//name");
        System.out.println(node.getName()+":"+node.getText());
        fis.close();
    }
}

1.4 XPATH解析(有條件的網址)

public class Demo4 {
    public static void main(String[] args) throws IOException, DocumentException {
        String phone="17845109827";
        URL url=new URL("http://apis.juhe.cn/mobile/get? phone="+phone+"&dtype=xml&key=9f3923e8f87f1ea50ed4ec8c39cc9253");
        URLConnection conn = url.openConnection();
        InputStream is = conn.getInputStream();
        SAXReader sr=new SAXReader();
        Document doc = sr.read(is);
        Node node = doc.selectSingleNode("//company");
        System.out.println("運營商:"+node.getText());
    }
}

1.5 XML生成

public class Demo5 {
    public static void main(String[] args) throws IOException {
        Document doc= DocumentHelper.createDocument();
        Element books = doc.addElement("books");
        for(int i=0;i<100;i++){
            Element book = books.addElement("book");
            Element name = book.addElement("name");
            name.setText(i+"種蘋果的小姑娘");
            Element info = book.addElement("info");
            info.setText(i+"辛勤種植蘋果的故事");
            book.addAttribute("id",100+i+"");
        }
        FileOutputStream fos=new FileOutputStream("f://books.xml");
        XMLWriter xw=new XMLWriter();
        xw.write(doc);
        xw.close();
        System.out.println("執行完畢");
    }
}

1.6 XStream方式生成XML

Person p=new Person();
        Person p1=new Person("李四",19);
        p.setName("張三");
        p.setAge(18);
        XStream x=new XStream();
        x.alias("person",Person.class);
        String s1 = x.toXML(p);
        String s2 = x.toXML(p1);
        System.out.println(s1);
        System.out.println(s2);

2 JSON知識點

2.1 物件轉Json(Gson)

public class Demo1 {
    public static void main(String[] args) {
        /*Gson g=new Gson();
        Book b=new Book("100","金蘋果","種植蘋果真辛苦");
        String s = g.toJson(b);
        System.out.println(s);*/
        Book b=new Book("100","金蘋果","種植蘋果真辛苦");
        String s = new Gson().toJson(b);
        System.out.println(s);
    }
}

2.2 Json轉物件(Gson)

public class Demo2 {
    public static void main(String[] args) {
        Gson g=new Gson();
        Book b = g.fromJson("{\"id\":\"100\",\"neme\":\"金蘋果\",\"info\":\"種植蘋果真辛苦\"}", Book.class);
        System.out.println(b.getId());
    }
}

2.3 Json轉集合(Gson)

public class Demo3 {
    public static void main(String[] args) {
        /*Gson g=new Gson();
        HashMap data = g.fromJson("{\"id\":\"100\",\"neme\":\"金蘋果\",\"info\":\"種植蘋果真辛苦\"}", HashMap.class);
        System.out.println(data.get("id"));*/
        Gson g=new Gson();
        //{"id":"100","neme":"金蘋果","info":"種植蘋果真辛苦","page":["鋤禾日當午","汗滴禾下土","嘿嘿嘿嘿嘿"]}
        HashMap data = g.fromJson("{\"id\":\"100\",\"neme\":\"金蘋果\",\"info\":\"種植蘋果真辛苦\",\"page\":[\"鋤禾日當午\",\"汗滴禾下土\",\"嘿嘿嘿嘿嘿\"]}", HashMap.class);
        //System.out.println(data.get("page").getClass());
        List page = (List) data.get("page");
        System.out.println(page.get(1));

    }
}

2.4 物件轉Json(fastJson)

public class Demo4 {
    public static void main(String[] args) {
        Book b=new Book("1002","唐詩三百首","床前明月光,疑是地上霜,舉頭望明月,低頭思故鄉");
        String s = JSON.toJSONString(b);
        System.out.println(s);
    }
}

2.5 Json轉物件(fastJson)

public class Demo5 {
    public static void main(String[] args) {
        //{"id":"1002","info":"床前明月光,疑是地上霜,舉頭望明月,低頭思故鄉","neme":"唐詩三百首"}
        Book book = JSON.parseObject("{\"id\":\"1002\",\"info\":\"床前明月光,疑是地上霜,舉頭望明月,低頭思故鄉\",\"neme\":\"唐詩三百首\"}",Book.class);
        System.out.println(book.getInfo());
    }
}

2.6 Json轉集合(fastJson)

public class Demo6 {
    public static void main(String[] args) {
        List<String> list = JSON.parseArray("[\"一二三\",\"四五六\",\"七八九\"]", String.class);
        System.out.println(list.get(1));
    }
}