json格式如下:
{"reposts_count": 0, "mlevel": 0, "user_id": 1620302927, "retweeted_status": {"reposts_count": 1, "user_id": 2209251457, "text": "\u4e24\u6735\u5c0f\u83ca\u82b1\u554a,\u5f00\u5728\u82b1\u4e1b\u4e2d\u554a"}
数量有很多,是以txt文本存在D盘,现在的流程是这样:读取文本->解析Json,获得uid和text(将utf-8编码改为中文)->存入MySql数据库的retweetedWeibo表里,只有2个字段(uid,text)。
已经在网上找过很多java 解析json的代码,但有错,而且很乱,有的用的jar包,有的又不写清楚,搞的我要抓狂了简直。 要是大神们解决了我的问题,再加C币!
为什么大家都只看到了解析json,其他的呢?上面还写了其他的要求啊?而且,你们的解析Json代码我在网上都有看到过,有的还试过了。我其实想要的是完整版的代码。辛苦大家了。
我给你完整代码,说明如下
1).txt文本中的JSON数据格式是JSON数组格式形如:[{},{},{},{}],读取文本文件内容的方法是jsonRead
2)main方法是示例代码,parseArray是解析返回JSON数组中某个key的值,是个列表,对你的应用来说就是获取“retweeted_status"的值。parseObject是解析JSON对象的,行如{}的数据。
对你的应用来说就是获取retweeted_status对象的"user_id","text"两个属性值。
3)需要引用的jar是json-simple-1.1.1.jar。你去搜一个,添加到工程路径中。运行OK。
这个其实很简单的,一定要耐心点,别着急,慢慢来。我的源码如下:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JsonParseUtil {
private static JSONParser parser = new JSONParser();
/**
* 返回数组格式的JSON[]中某个属性值,如果属性是普通类型,则直接取出,如果是JSON对象,则需要转换
* @param json
* @param key
* @return
*/
public static List parseArray(String json,String key){
List result = new ArrayList();
try {
JSONArray array = (JSONArray) parser.parse(json);
for (int i = 0; i < array.size(); i++) {
JSONObject obj = (JSONObject) array.get(i);
Object value = obj.get(key);
String text = null;
if(value instanceof JSONObject){
text = ((JSONObject) value).toJSONString();
}else if(value instanceof String){
text = (String) value;
}
result.add(text);
}
} catch (ParseException e) {
e.printStackTrace();
}
return result;
}
/**
* JSON格式是{}的map数据,返回指定的key
* @param json
* @param keys
* @return
*/
public static Map<String,Object> parseObject(String json,List<String> keys){
Map<String,Object> result = new HashMap<String,Object> ();
if(json==null||"".equals(json)){
return result;
}
if(keys==null||keys.size()==0){
return result;
}
//利用json.simple解析JSON字符串
try {
JSONObject object = (JSONObject)parser.parse(json);
if(object!=null){
for(String key:keys){
result.put(key, object.get(key));
}
}
} catch (ParseException e) {
e.printStackTrace();
}
return result;
}
public static String jsonRead(String fileName) {
String json = null;
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(fileName));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
json = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return json;
}
public static void main(String[] args) {
//读取文件
String json = jsonRead("src/json.txt");
//首先得到的是retweeted_status的数组
List<String> retweeted_status = parseArray(json,"retweeted_status");
List<String> keys = new ArrayList<String>();
keys.add("user_id");
keys.add("text");
//再解析每个retweeted_status的内容
for(String info:retweeted_status){
Map<String,Object> map = parseObject(info,keys);
StringBuffer out = new StringBuffer();
for(String key:keys){
if(map!=null){
out.append(key+":"+map.get(key)+" ");
}
}
System.out.println("result:"+out.toString());
}
}
}
已经在网上找过很多java 解析json的代码,但有错,而且很乱,有的用的jar包,有的又不写清楚,搞的我要抓狂了简直。
可以用谷歌的json包,去年我就是用这个包解析的json格式数据,我记得我是将json格式数据存在一个字符串里然后用json包解析的.通过字段名去获取所需要的数据
去年我也是做的这个微博的数据采集.
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
public class test {
public static void main(String[] args) {
String json = "{'birth_day': 29,'edu':[{'departmentid':0,'id':24037,'level':3}, {'departmentid':0,'id':24037,'level':3},{'departmentid':0,'id':24037,'level':2}]}";
Gson gson = new Gson();
Map p = gson.fromJson(json, HashMap.class);
System.out.print(((List)p.get("edu")).get(0).get("level"));
}
}
这是我以前用的一个,json的内容类似把,可以借鉴.
用gson
参考:http://chinazzlm.blog.163.com/blog/static/16184353720126304435410/
String json = "{\"reposts_count\": 0, \"mlevel\": 0, \"user_id\": 1620302927, \"retweeted_status\": {\"reposts_count\": 1, \"user_id\": 2209251457, \"text\": \"\u4e24\u6735\u5c0f\u83ca\u82b1\u554a,\u5f00\u5728\u82b1\u4e1b\u4e2d\u554a\"}}";
JSONObject jo = JSON.parseObject(json);
System.out.println("userId:" + jo.getLongValue("user_id"));
JSONObject rs = jo.getJSONObject("retweeted_status");
System.out.println(rs.getLongValue("user_id"));
System.out.println(rs.getString("text"));
打印:
userId:1620302927
2209251457
两朵小菊花啊,开在花丛中啊
需要引入包的pom配置:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.37</version>
</dependency>
使用的是阿里巴巴的fastjson
private List getObjects(String json){
Gson gson = new Gson();
TypeToken> token = new TypeToken>() {
};
return gson.fromJson(json,token.getType());
}
Object即实体类,封装json对应的信息user_id、mlevel等等 ,
将获取到的字符串json通过标记token转出去即可获取相应的类型
使用google的Gson,附加工具类
package com.gy.utils;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.gy.constant.Constant;
public class JsonUtil {
private static final Log log = LogFactory.getLog(JsonUtil.class);
public static final String EMPTY = "";
/** 空的 {@code JSON} 数据 - <code>"{}"</code>。 */
public static final String EMPTY_JSON = "{}";
/** 空的 {@code JSON} 数组(集合)数据 - {@code "[]"}。 */
public static final String EMPTY_JSON_ARRAY = "[]";
/** {@code Google Gson} 的 {@literal @Since} 注解常用的版本号常量 - {@code 1.0}。 */
public static final Double SINCE_VERSION_10 = 1.0d;
/** {@code Google Gson} 的 {@literal @Since} 注解常用的版本号常量 - {@code 1.1}。 */
public static final Double SINCE_VERSION_11 = 1.1d;
/** {@code Google Gson} 的 {@literal @Since} 注解常用的版本号常量 - {@code 1.2}。 */
public static final Double SINCE_VERSION_12 = 1.2d;
/**
* 将给定的目标对象根据指定的条件参数转换成 {@code JSON} 格式的字符串。
* <strong>该方法转换发生错误时,不会抛出任何异常。
* 若发生错误时,曾通对象返回 <code>"{}"</code>; 集合或数组对象返回<code>"[]"</code></strong>
* @param target 目标对象。
* @param targetType 目标对象的类型。
* @param isSerializeNulls 是否序列化 {@code null} 值字段。
* @param version 字段的版本号注解。
* @param datePattern 日期字段的格式化模式。
* @param excludesFieldsWithoutExpose 是否排除未标注 {@literal @Expose} 注解的字段。
* @return 目标对象的 {@code JSON} 格式的字符串。
*/
public static String toJson(Object target, Type targetType, boolean isSerializeNulls,
Double version, String datePattern, boolean excludesFieldsWithoutExpose) {
if (target == null)
return EMPTY_JSON;
GsonBuilder builder = new GsonBuilder();
if (isSerializeNulls)
builder.serializeNulls();
if (version != null)
builder.setVersion(version.doubleValue());
if (StringUtils.isEmpty(datePattern))
datePattern = Constant.DATE_LONG_V;
builder.setDateFormat(datePattern);
if (excludesFieldsWithoutExpose)
builder.excludeFieldsWithoutExposeAnnotation();
String result = EMPTY;
Gson gson = builder.create();
try {
if (targetType != null) {
result = gson.toJson(target, targetType);
} else {
result = gson.toJson(target);
}
} catch (Exception ex) {
log.warn("目标对象 " + target.getClass().getName()
+ " 转换 JSON 字符串时,发生异常!", ex);
if (target instanceof Collection || target instanceof Iterator
|| target instanceof Enumeration
|| target.getClass().isArray()) {
result = EMPTY_JSON_ARRAY;
} else
result = EMPTY_JSON;
}
return result;
}
/**
* 将给定的目标对象转换成 {@code JSON} 格式的字符串。
* <strong>此方法只用来转换普通的 {@code JavaBean}对象。</strong>
* <ul>
* <li>该方法只会转换标有 {@literal @Expose} 注解的字段;</li>
* <li>该方法不会转换 {@code null} 值字段;</li>
* <li>该方法会转换所有未标注或已标注 {@literal @Since} 的字段;</li>
* <li>该方法转换时使用默认的 日期/时间 格式化模式 - {@code yyyy-MM-dd HH:mm:ss};</li>
* </ul>
* @param target 要转换成 {@code JSON} 的目标对象。
* @return 目标对象的 {@code JSON} 格式的字符串。
*/
public static String toJson(Object target) {
return toJson(target, null, false, null, null, true);
}
/**
* 将给定的目标对象转换成 {@code JSON} 格式的字符串。
* <strong>此方法只用来转换普通的 {@code JavaBean}对象。</strong>
* <ul>
* <li>该方法只会转换标有 {@literal @Expose} 注解的字段;</li>
* <li>该方法不会转换 {@code null} 值字段;</li>
* <li>该方法会转换所有未标注或已标注 {@literal @Since} 的字段;</li>
* </ul>
* @param target 要转换成 {@code JSON} 的目标对象。
* @param datePattern 日期字段的格式化模式。
* @return 目标对象的 {@code JSON} 格式的字符串。
*/
public static String toJson(Object target, String datePattern) {
return toJson(target, null, false, null, datePattern, true);
}
/**
* 将给定的目标对象转换成 {@code JSON} 格式的字符串。
* <strong>此方法只用来转换普通的 {@code JavaBean}对象。</strong>
* <ul>
* <li>该方法只会转换标有 {@literal @Expose} 注解的字段;</li>
* <li>该方法不会转换 {@code null} 值字段;</li>
* <li>该方法转换时使用默认的 日期/时间 格式化模式 - {@code yyyy-MM-dd HH:mm:ss};</li>
* </ul>
* @param target 要转换成 {@code JSON} 的目标对象。
* @param version 字段的版本号注解({@literal @Since})。
* @return 目标对象的 {@code JSON} 格式的字符串。
*/
public static String toJson(Object target, Double version) {
return toJson(target, null, false, version, null, true);
}
/**
* 将给定的目标对象转换成 {@code JSON} 格式的字符串。
* <strong>此方法只用来转换普通的 {@code JavaBean}对象。</strong>
* <ul>
* <li>该方法不会转换 {@code null} 值字段;</li>
* <li>该方法会转换所有未标注或已标注 {@literal @Since} 的字段;</li>
* <li>该方法转换时使用默认的 日期/时间 格式化模式 - {@code yyyy-MM-dd HH:mm:ss};</li>
* </ul>
* @param target 要转换成 {@code JSON} 的目标对象。
* @param excludesFieldsWithoutExpose 是否排除未标注 {@literal @Expose} 注解的字段。
* @return 目标对象的 {@code JSON} 格式的字符串。
*/
public static String toJson(Object target, boolean excludesFieldsWithoutExpose) {
return toJson(target, null, false, null, null, excludesFieldsWithoutExpose);
}
/**
* 将给定的目标对象转换成 {@code JSON} 格式的字符串。
* <strong>此方法只用来转换普通的 {@code JavaBean}对象。</strong>
* <ul>
* <li>该方法不会转换 {@code null} 值字段;</li>
* <li>该方法转换时使用默认的 日期/时间 格式化模式 - {@code yyyy-MM-dd HH:mm:ss};</li>
* </ul>
* @param target 要转换成 {@code JSON} 的目标对象。
* @param version 字段的版本号注解({@literal @Since})。
* @param excludesFieldsWithoutExpose 是否排除未标注 {@literal @Expose} 注解的字段。
* @return 目标对象的 {@code JSON} 格式的字符串。
*/
public static String toJson(Object target, Double version, boolean excludesFieldsWithoutExpose) {
return toJson(target, null, false, version, null, excludesFieldsWithoutExpose);
}
/**
* 将给定的目标对象转换成 {@code JSON} 格式的字符串。
* <strong>此方法通常用来转换使用泛型的对象。</strong>
* <ul>
* <li>该方法只会转换标有 {@literal @Expose} 注解的字段;</li>
* <li>该方法不会转换 {@code null} 值字段;</li>
* <li>该方法会转换所有未标注或已标注 {@literal @Since} 的字段;</li>
* <li>该方法转换时使用默认的 日期/时间 格式化模式 - {@code yyyy-MM-dd HH:mm:ss};</li>
* </ul>
* @param target 要转换成 {@code JSON} 的目标对象。
* @param targetType 目标对象的类型。
* @return 目标对象的 {@code JSON} 格式的字符串。
*/
public static String toJson(Object target, Type targetType) {
return toJson(target, targetType, false, null, null, true);
}
/**
* 将给定的目标对象转换成 {@code JSON} 格式的字符串。<strong>此方法通常用来转换使用泛型的对象。</strong>
* <ul>
* <li>该方法只会转换标有 {@literal @Expose} 注解的字段;</li>
* <li>该方法不会转换 {@code null} 值字段;</li>
* <li>该方法转换时使用默认的 日期/时间 格式化模式 - {@code yyyy-MM-dd HH:mm:ss};</li>
* </ul>
* @param target 要转换成 {@code JSON} 的目标对象。
* @param targetType 目标对象的类型。
* @param version 字段的版本号注解({@literal @Since})。
* @return 目标对象的 {@code JSON} 格式的字符串。
*/
public static String toJson(Object target, Type targetType, Double version) {
return toJson(target, targetType, false, version, null, true);
}
/**
* 将给定的目标对象转换成 {@code JSON} 格式的字符串。<strong>此方法通常用来转换使用泛型的对象。</strong>
* <ul>
* <li>该方法不会转换 {@code null} 值字段;</li>
* <li>该方法会转换所有未标注或已标注 {@literal @Since} 的字段;</li>
* <li>该方法转换时使用默认的 日期/时间 格式化模式 - {@code yyyy-MM-dd HH:mm:ss};</li>
* </ul>
* @param target 要转换成 {@code JSON} 的目标对象。
* @param targetType 目标对象的类型。
* @param excludesFieldsWithoutExpose 是否排除未标注 {@literal @Expose} 注解的字段。
* @return 目标对象的 {@code JSON} 格式的字符串。
*/
public static String toJson(Object target, Type targetType, boolean excludesFieldsWithoutExpose) {
return toJson(target, targetType, false, null, null, excludesFieldsWithoutExpose);
}
/**
* 将给定的目标对象转换成 {@code JSON} 格式的字符串。<strong>此方法通常用来转换使用泛型的对象。</strong>
* <ul>
* <li>该方法不会转换 {@code null} 值字段;</li>
* <li>该方法转换时使用默认的 日期/时间 格式化模式 - {@code yyyy-MM-dd HH:mm:ss};</li>
* </ul>
* @param target 要转换成 {@code JSON} 的目标对象。
* @param targetType 目标对象的类型。
* @param version 字段的版本号注解({@literal @Since})。
* @param excludesFieldsWithoutExpose 是否排除未标注 {@literal @Expose} 注解的字段。
* @return 目标对象的 {@code JSON} 格式的字符串。
*/
public static String toJson(Object target, Type targetType, Double version,
boolean excludesFieldsWithoutExpose) {
return toJson(target, targetType, false, version, null, excludesFieldsWithoutExpose);
}
/**
* 将给定的 {@code JSON} 字符串转换成指定的类型对象。
* @param <T> 要转换的目标类型。
* @param json 给定的 {@code JSON} 字符串。
* @param token {@code com.google.gson.reflect.TypeToken} 的类型指示类对象。
* @param datePattern 日期格式模式。
* @return 给定的 {@code JSON} 字符串表示的指定的类型对象。
*/
public static <T> T fromJson(String json, TypeToken<T> token, String datePattern) {
if (StringUtils.isEmpty(json)) {
return null;
}
GsonBuilder builder = new GsonBuilder();
if (StringUtils.isEmpty(datePattern)) {
datePattern = Constant.DATE_LONG_V;
}
Gson gson = builder.create();
try {
return gson.fromJson(json, token.getType());
} catch (Exception ex) {
log.error(json + " 无法转换为 " + token.getRawType().getName() + " 对象!", ex);
return null;
}
}
/**
* 将给定的 {@code JSON} 字符串转换成指定的类型对象。
* @param <T> 要转换的目标类型。
* @param json 给定的 {@code JSON} 字符串。
* @param token {@code com.google.gson.reflect.TypeToken} 的类型指示类对象。
* @return 给定的 {@code JSON} 字符串表示的指定的类型对象。
*/
public static <T> T fromJson(String json, TypeToken<T> token) {
return fromJson(json, token, null);
}
/**
* 将给定的 {@code JSON} 字符串转换成指定的类型对象。
* <strong>此方法通常用来转换普通的 {@code JavaBean}对象。</strong>
* @param <T> 要转换的目标类型。
* @param json 给定的 {@code JSON} 字符串。
* @param clazz 要转换的目标类。
* @param datePattern 日期格式模式。
* @return 给定的 {@code JSON} 字符串表示的指定的类型对象。
*/
public static <T> T fromJson(String json, Class<T> clazz, String datePattern) {
if (StringUtils.isEmpty(json)) {
return null;
}
GsonBuilder builder = new GsonBuilder();
if (StringUtils.isEmpty(datePattern)) {
datePattern = Constant.DATE_LONG_V;
}
Gson gson = builder.create();
try {
return gson.fromJson(json, clazz);
} catch (Exception ex) {
log.error(json + " 无法转换为 " + clazz.getName() + " 对象!", ex);
return null;
}
}
/**
* 将给定的 {@code JSON} 字符串转换成指定的类型对象。
* <strong>此方法通常用来转换普通的 {@code JavaBean}对象。</strong>
* @param <T> 要转换的目标类型。
* @param json 给定的 {@code JSON} 字符串。
* @param clazz 要转换的目标类。
* @return 给定的 {@code JSON} 字符串表示的指定的类型对象。
*/
public static <T> T fromJson(String json, Class<T> clazz) {
return fromJson(json, clazz, null);
}
}
用这个包net.slf.json
http://www.cnblogs.com/lanxuezaipiao/archive/2013/05/24/3096437.html