JSONObject,JSONArray,百度api的使用

前端之家收集整理的这篇文章主要介绍了JSONObject,JSONArray,百度api的使用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
package com.imooc.miaosha.util.translate;


import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**  * User: wupeng  * Date: 2018/6/24 0024 下午 12:17  * Desc:  */ public class translateUtils {
    // 在平台申请的APP_ID 详见 http://api.fanyi.baidu.com/api/trans/product/desktop?req=developer
    private static final String APP_ID = "";
    private static final String SECURITY_KEY = "";


    /**  * demo  * @param args  */  public static void main(String[] args) {

        String query = "hello";
        translateUtils.getChinese(query);
        System.out.println();
    }

    /**  * 1.解析json字符串 {"from":"en","to":"zh","trans_result":[{"src":"hello","dst":"\u4f60\u597d"}]}  * 2.转换成JSONObject 通过(fromObject方法 * 3.转换成JSONArray 转换成getJSONObject  * maven依赖  * <dependency>  * <groupId>net.sf.json-lib</groupId>  * <artifactId>json-lib</artifactId>  * <version>2.4</version>  * <classifier>jdk15</classifier>  * </dependency>  * @param query  * @return  */  public static String getChinese(String query){
        TransApi api = new TransApi(APP_ID,SECURITY_KEY);
        String data  = api.getTransResult(query,"auto","zh");
        System.out.println(data);
        JSONObject jsonObject = JSONObject.fromObject(data);
        String transResult =  jsonObject.get("trans_result").toString();

        JSONArray results = JSONArray.fromObject(transResult);
        JSONObject result = results.getJSONObject(0);
        String translateDate = result.get("dst").toString();
        System.out.println( result.get("dst"));
        return translateDate;
}
}
原文链接:https://www.f2er.com/json/288559.html

猜你在找的Json相关文章