1、连接redis
Jedis jedis = new Jedis("localhost", 6379);
2、将字符串转为json格式
JSONObject js=JSONObject.fromObject(jsonStr);
3、对json格式进行解析
4、将json写入redis
java
public static void RedisSet(JSONObject js,Jedis js01)
{
//获取json中的所有key
Set<String>keys=js.keySet();
//遍历所有的key,将数据写入redis
for(String key:keys)
{
//判断是否是多层镶嵌json
if(isJSON(js.getString(key)))
{
//将内层json字符串转为json格式
JSONObject js1=JSONObject.fromObject(js.getString(key));
//递归调用解析json格式
RedisSet(js1,js01);
}
//将数据写入redis
js01.set(key,js.getString(key));
}
}
5、判断字符串是否为json格式
java
public static Boolean isJSON(String str)
{
String pattern = "^\\{.*}$|^\\[.*]$";
return str.matches(pattern);
}
6、关闭连接
java
redis.close;
7、关闭连接
java
return ture;
return false
全部代码
java
public static Boolean isJSON(String str)
{
String pattern = "^\\{.*}$|^\\[.*]$";
return str.matches(pattern);
}
public static void RedisSet(JSONObject js,Jedis js01)
{
Set<String>keys=js.keySet();
for(String key:keys)
{
if(isJSON(js.getString(key)))
{
JSONObject js1=JSONObject.fromObject(js.getString(key));
RedisSet(js1,js01);
}
js01.set(key,js.getString(key));
}
}
@Override
public JSONObject Innomind(String jsonStr)
{
Jedis jedis = new Jedis("localhost", 6379);
JSONObject js=JSONObject.fromObject(jsonStr);
RedisSet(js,js01);
js01.close();
return js;
}
//测试数据
{
"jsonStr":"{\"ip\":\"\",\"address\":{\"city\":\"New York\",\"Zip\":\"10086\",\"address01\":{\"city01\":\"New York01\",\"Zip01\":\"10087777\"}}}"
}