java怎么读取json格式的数据

java怎么读取json格式的数据,第1张

java可以使用JSONObject和JSONArray来 *** 作json对象和json数组,具体用法如下

1:java对象与json串转换:

java对象—json串:

JSONObject JSONStr = JSONObject.fromObject(object)

String str = JSONStr.toString()

json串—java对象:

JSONObject jsonObject = JSONObject.fromObject( jsonString )

Object pojo = JSONObject.toBean(jsonObject,pojoCalss)

2:java数组对象与json串转换:

java数组—json串:

JSONArray arrayStr = JSONArray.fromObject(List<?>)

String str = arrayStr.toString()

json串—java数组:

JSONArray array = JSONArray.fromObject(str)

List<?>list = JSONArray.toList(array, ?.class)

String fullFileName = "E:/a.json"

File file = new File(fullFileName)

Scanner scanner = null

StringBuilder buffer = new StringBuilder()

try {

scanner = new Scanner(file, "utf-8")

while (scanner.hasNextLine()) {

buffer.append(scanner.nextLine())

}

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

} finally {

if (scanner != null) {

scanner.close()

}

}

System.out.println(buffer.toString())

这是读取文件的方法,至于解析json,则你自己弄吧

String json = [{\"foo\": \"bar\"},{\"foo\": \"biz\"}]"

JsonFactory f = new JsonFactory()

JsonParser jp = f.createJsonParser(json)

// advance stream to START_ARRAY first:

jp.nextToken()

// and then each time, advance to opening START_OBJECT

while (jp.nextToken() == JsonToken.START_OBJECT)) {

Foo foobar = mapper.readValue(jp, Foo.class)

// process

// after binding, stream points to closing END_OBJECT

}

public class Foo {

public String foo

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/12038812.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-20
下一篇 2023-05-20

发表评论

登录后才能评论

评论列表(0条)

保存