Java转换Json教程以及常见的错误

源码及jar包下载地址:

https://gitee.com/jahero/json.git

Java程序转换json常用的6个jar包:

commons-logging-1.0.4.jar
commons-lang-2.3.jar
commons-collections-3.2.jar
commons-beanutils-1.7.0.jar
json-lib-2.2.1-jdk15.jar
ezmorph-1.0.4.jar

如果缺少以上的jar包或者版本不对会报各种各样的错误,如下:

缺少commons-beanutils-1.8.0.jar:

java.lang.NoClassDefFoundError: org/apache/commons/beanutils/DynaBean 

缺少commons-lang-2.4.jar:

java.lang.NoClassDefFoundError: org/apache/commons/lang/exception/NestableRuntimeException

缺少commons-collections.jar:

java.lang.NoClassDefFoundError: org/apache/commons/collections/map/ListOrderedMap

缺少commons-logging-1.1.1.jar:

java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory 

缺少ezmorph-1.0.4.jar:

java.lang.NoClassDefFoundError: net/sf/ezmorph/Morpher 

缺少json-lib-2.3-jdk15.jar:

java.lang.NoClassDefFoundError: net/sf/json/JSONObject 

Java转换Json教程

一个小Demo,TemplateJsonForJava

import net.sf.json.JSONObject;
import com.bao.util.Utils;
import java.util.HashMap;
import java.util.Map;
/**
 * Java下转换json模板
 * 
 * @author hao
 */
public class TemplateJsonForJava {
  public static final String url_Address = "http://www.wqyunpan.com/bookQr/resource/resDetail";// 地址
  // public static final String id = "43626";// 参数
  public static String SelectDownUrl(int id) {
    String result = null;
    String videoUrl = null;
    String url = url_Address;
    Map params = new HashMap();// 请求参数
    params.put("id", id);//
    try {
      result = Utils.net(url, params, "GET");
      JSONObject object = JSONObject.fromObject(result);
      // System.err.println(object);
      if (object != null) {
        JSONObject item = object.optJSONObject("item");
        videoUrl = item.getString("downUrl");// 解析第二次json取出URL
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
    return videoUrl;
  }
}

其中用到的工具类Utils

package com.bao.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

/**
 * 工具类
 * 
 * @author hao
 *
 */
public class Utils {
  public static final String DEF_CHATSET = "UTF-8";
  public static final int DEF_CONN_TIMEOUT = 30000;
  public static final int DEF_READ_TIMEOUT = 30000;
  public static String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";

  /**
   * 网络请求
   * 
   * @param strUrl
   *            请求地址
   * @param params
   *            请求参数
   * @param method
   *            请求方法
   * @return 网络请求字符串
   * @throws Exception
   */
  public static String net(String strUrl, Map params, String method) throws Exception {
    HttpURLConnection conn = null;
    BufferedReader reader = null;
    String rs = null;
    try {
      StringBuffer sb = new StringBuffer();
      if (method == null || method.equals("GET")) {
        strUrl = strUrl + "?" + urlencode(params);
      }
      URL url = new URL(strUrl);
      conn = (HttpURLConnection) url.openConnection();
      if (method == null || method.equals("GET")) {
        conn.setRequestMethod("GET");
      } else {
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
      }
      conn.setRequestProperty("User-agent", userAgent);
      conn.setUseCaches(false);
      conn.setConnectTimeout(DEF_CONN_TIMEOUT);
      conn.setReadTimeout(DEF_READ_TIMEOUT);
      conn.setInstanceFollowRedirects(false);
      conn.connect();
      if (params != null && method.equals("POST")) {
        try {
          DataOutputStream out = new DataOutputStream(conn.getOutputStream());
          out.writeBytes(urlencode(params));
        } catch (Exception e) {
          // TODO: handle exception
          e.printStackTrace();
        }
      }
      InputStream is = conn.getInputStream();
      reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
      String strRead = null;
      while ((strRead = reader.readLine()) != null) {
        sb.append(strRead);
      }
      rs = sb.toString();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (reader != null) {
        reader.close();
      }
      if (conn != null) {
        conn.disconnect();
      }
    }
    return rs;
  }

  /**
   * 将map型转为请求参数型String
   * 
   * @param data
   * @return
   */
  public static String urlencode(Map<String, String> data) {
    StringBuilder sb = new StringBuilder();
    for (Map.Entry i : data.entrySet()) {
      try {
        sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "", "UTF-8")).append("&");
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }
    }
    return sb.toString();
  }

  /**
   * 获取当前时间,格式为2019-01-01
   * 
   * @return
   */
  public static String GetNowDate_Day() {
    Date currentTime = new Date();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    String dateString = formatter.format(currentTime);
    return dateString;
  }

  /**
   * 获取当前时间,格式为 2019-02-26 15:11:44
   * 
   * @return
   */
  public static String GetNowDate() {
    Date currentTime = new Date();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String dateString = formatter.format(currentTime);
    return dateString;
  }

  /**
   * 获取今天是周几
   * 
   * @return
   */
  public static String GetTodsyWeek() {
    final String dayNames[] = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
    Calendar calendar = Calendar.getInstance();
    Date date = new Date();
    calendar.setTime(date);
    int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
    if (dayOfWeek < 0) {
      dayOfWeek = 0;
    }
    return (dayNames[dayOfWeek]);
  }

  /**
   * 模仿写系统运行日志
   * 
   * @return
   * JavaWeb中读取文件资源的路径问题参考链接:https://www.cnblogs.com/Buffalo-L/p/4468483.html
   */
  public static void WriteLog(String text, String path) {
    try {
      String data = "当前执行的任务为:" + text + ", 时间为:【" + Utils.GetNowDate() +"】";
//      File file = new File("/home/hao/Desktop/TimerLog.txt");
      File file = new File(path);
      FileOutputStream fos = null;
      fos = new FileOutputStream(file, true);// 这里构造方法多了一个参数true,表示在文件末尾追加写入
      OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");// 指定以UTF-8格式写入文件
      osw.write(data + "。");
      // 每写入一个Map就换一行
      osw.write("\r\n");
      // 写入完成关闭流
      osw.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

}

其中还有使用短信接口、发送邮件等等

原文发布于微信公众号 - 浩Coding(gh_c4a2e63d2ca7)

原文发表时间:2019-03-26

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券