zoukankan      html  css  js  c++  java
  • 获取JSON格式的字符串各个属性对应的值

    {"lastrdtime":1515998187379,"creditbalance":"$5.00","contactmode":"0100000003","consname":"100000030060","consno":"100000030060","consaddr":"北京市海淀区中关村","lastreading":"125.00"}

    现在有上面JSON格式的字符串, 如何获取consno对应的值100000030060?

    ==方式一:Google的Gson.================================================

    1.基于maven,导入谷歌的Gson包:

    <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.2</version>
    </dependency>

    2.创建Gson对象, 将JSON字符串转为Map对象, Map取值就哦了.(转成自定义的javaBean, 通过getXxx()取值也可以)

    Gson gson = new Gson();
    Map map = gson.fromJson(stringEntity, Map.class);
    System.out.println(map.get("consno"));

    结果:

    100000030060

    ==方式二:阿里的FastJson.================================================

    1.基于maven, 导入阿里的FastJson包:

    <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.41</version>
    </dependency>

    2.调用JSON类的parseObject方法, 将字符串转为JSONObject:

    JSONObject jsonObject = JSON.parseObject(jsonEntity);
    System.out.println(jsonObject.get("consno"));

    结果:

    100000030060

    附:

    package com.test.com.pers.others;
    
    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONObject;
    import com.google.gson.Gson;
    
    import java.util.Map;
    
    /**
     * Created by yadongliang on 2018/1/15 0015.
     */
    public class GetJsonParameter {
        public static void main(String[] args) {
            String stringEntity = "{'consno':'100000030060','consaddr':'北京市海淀区中关村'}";
            /**
             * 方式一:Google的Gson.
             */
            Gson gson = new Gson();
            Map map = gson.fromJson(stringEntity, Map.class);
            System.out.println(map.get("consno"));
            System.out.println(map.get("consaddr"));
    
            /**
             * 方式二:阿里的FastJson.
             */
            JSONObject jsonObject = JSON.parseObject(stringEntity);
            System.out.println(jsonObject.get("consno"));
            System.out.println(jsonObject.get("consaddr"));
            System.out.println(jsonObject.getString("consno"));
            System.out.println(jsonObject.getString("consaddr"));
    
        }
    }
    View Code

    另, 可参考另一篇:FastJson对于JSON格式字符串、JSON对象及JavaBean之间的相互转换

    这篇讲的更细致...

  • 相关阅读:
    Java DES 测试
    HttpClient3.1 警告: Cookie rejected:
    WebService实现文件上传下载
    使用dom4j生成xml字符串,以及解析xml字符串
    Java 单例总结
    weblogic使用脚本部署
    Java比较两个日期的大小
    Ubuntu14.04 weblogic11g集群环境测试
    Gson 禁止特殊字符转码
    只用CSS做到完全居中
  • 原文地址:https://www.cnblogs.com/yadongliang/p/8288590.html
Copyright © 2011-2022 走看看