
先将java对象转换为json对象,在将json对象转换为json字符串
JSONObject json = JSONObject.fromObject(obj)//将java对象转换为json对象
String str = json.toString()//将json对象转换为字符串
参考代码如下:
package baz.parse
import java.util.ArrayList
import java.util.List
import net.sf.json.JSON
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import net.sf.json.JSONSerializer
import baz.bean.Person
public class ParseJson {
private String jsonStr
public ParseJson() {
}
public ParseJson(String str){
this.jsonStr = str
}
/**
* 解析json字符串
*/
public void parse(){
JSONObject jsonObject = JSONObject.fromObject(jsonStr)
String name = jsonObject.getString("name")
int num = jsonObject.getInt("num")
String sex = jsonObject.getString("sex")
int age = jsonObject.getInt("age")
System.out.println(name + " " + num + " " + sex + " " + age)
}
//将json字符串转换为java对象
public Person JSON2Object(){
//接收{}对象,此处接收数组对象会有异常
if(jsonStr.indexOf("[") != -1){
jsonStr = jsonStr.replace("[", "")
}
if(jsonStr.indexOf("]") != -1){
jsonStr = jsonStr.replace("]", "")
}
JSONObject obj = new JSONObject().fromObject(jsonStr)//将json字符串转换为json对象
Person jb = (Person)JSONObject.toBean(obj,Person.class)//将建json对象转换为Person对象
return jb//返回一个Person对象
}
}
PHP取Mysql数据并转换为json格式,这很简单 过程分为取数据-保存为数组-json格式输出三步 取数据分为连接与查询(条件等)。保存为数组也容易,array_push就行 json格式的输换最为便捷,只需echo json_encode($myArr)即可存成json文件
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)