当前位置:首页 » 编程语言 » java处理json字符串

java处理json字符串

发布时间: 2023-06-03 20:27:05

❶ 怎样从java后台获取json字符串并转换为json对象输出

使用json-lib.jar这个工具x0dx0apublic String getJson(Object obj){x0dx0a JSONObject json;x0dx0a json = JSONObject.fromObject(obj);x0dx0a return json.toString();x0dx0a}x0dx0a使用jquery来处理jsonx0dx0a//转换为json数据 datas可以用ajax从后台获取上面getJson中的数据x0dx0avar jsonDatas = eval("(" + datas + ")");x0dx0a //循环遍历数据x0dx0ajQuery.each(jsonDatas, function(item) {x0dx0a//循环x0dx0a});

❷ Java解析json数据

一、 JSON (JavaScript Object Notation)一种简单的数据格式,比xml更轻巧。
Json建构于两种结构:
1、“名称/值”对的集合(A collection of name/value pairs)。不同的语言中,它被理解为对象(object),纪录(record),结构(struct),字典(dictionary),哈希表(hash table),有键列表(keyed list),或者关联数组 (associative array)。 如:
{
“name”:”jackson”,
“age”:100
}

2、值的有序列表(An ordered list of values)。在大部分语言中,它被理解为数组(array)如:
{
“students”:
[
{“name”:”jackson”,“age”:100},
{“name”:”michael”,”age”:51}
]
}
二、java解析JSON步骤
A、服务器端将数据转换成json字符串
首先、服务器端项目要导入json的jar包和json所依赖的jar包至builtPath路径下(这些可以到JSON-lib官网下载:http://json-lib.sourceforge.net/)

然后将数据转为json字符串,核心函数是:
public static String createJsonString(String key, Object value)
{
JSONObject jsonObject = new JSONObject();
jsonObject.put(key, value);
return jsonObject.toString();
}
B、客户端将json字符串转换为相应的javaBean
1、客户端获取json字符串(因为android项目中已经集成了json的jar包所以这里无需导入)
public class HttpUtil
{

public static String getJsonContent(String urlStr)
{
try
{// 获取HttpURLConnection连接对象
URL url = new URL(urlStr);
HttpURLConnection httpConn = (HttpURLConnection) url
.openConnection();
// 设置连接属性
httpConn.setConnectTimeout(3000);
httpConn.setDoInput(true);
httpConn.setRequestMethod("GET");
// 获取相应码
int respCode = httpConn.getResponseCode();
if (respCode == 200)
{
return ConvertStream2Json(httpConn.getInputStream());
}
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}

private static String ConvertStream2Json(InputStream inputStream)
{
String jsonStr = "";
// ByteArrayOutputStream相当于内存输出流
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
// 将输入流转移到内存输出流中
try
{
while ((len = inputStream.read(buffer, 0, buffer.length)) != -1)
{
out.write(buffer, 0, len);
}
// 将内存流转换为字符串
jsonStr = new String(out.toByteArray());
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonStr;
}
}
2、获取javaBean
public static Person getPerson(String jsonStr)
{
Person person = new Person();
try
{// 将json字符串转换为json对象
JSONObject jsonObj = new JSONObject(jsonStr);
// 得到指定json key对象的value对象
JSONObject personObj = jsonObj.getJSONObject("person");
// 获取之对象的所有属性
person.setId(personObj.getInt("id"));
person.setName(personObj.getString("name"));
person.setAddress(personObj.getString("address"));
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}

return person;
}

public static List<Person> getPersons(String jsonStr)
{
List<Person> list = new ArrayList<Person>();

JSONObject jsonObj;
try
{// 将json字符串转换为json对象
jsonObj = new JSONObject(jsonStr);
// 得到指定json key对象的value对象
JSONArray personList = jsonObj.getJSONArray("persons");
// 遍历jsonArray
for (int i = 0; i < personList.length(); i++)
{
// 获取每一个json对象
JSONObject jsonItem = personList.getJSONObject(i);
// 获取每一个json对象的值
Person person = new Person();
person.setId(jsonItem.getInt("id"));
person.setName(jsonItem.getString("name"));
person.setAddress(jsonItem.getString("address"));
list.add(person);
}
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}

return list;
}

❸ java解析json字符串 放到数组中

java解析json字符串时将大括号中的对应为一个类,里面的数据对应为类的属性,最后用数组接受即可。

示例关键代码如下:

//导入net.sf.json.JSONArray和net.sf.json.JSONObject两个jar包

Stringstr="[{name:'a',value:'aa'},{name:'b',value:'bb'},{name:'c',value:'cc'},{name:'d',value:'dd'}]";//一个未转化的字符串
JSONArrayjson=JSONArray.fromObject(str);//首先把字符串转成JSONArray对象
if(json.size()>0){
for(inti=0;i<json.size();i++){
JSONObjectjob=json.getJSONObject(i);//遍历jsonarray数组,把每一个对象转成json对象
System.out.println(job.get("name")+"=");//得到每个对象中的属性值
}
}

❹ JAVA中如何将一个json形式的字符串转为json对象

org.json.jsonobject
去下一个这个jar包吧。
是专用处理json字符串的。
你的这个需求如果对象单一完成可以半自动化完成。
jsonobject
json
=
new
jsonobject(json字符串)
;
if(json.has("你要解析的json是否存在")){
//.....创建你的对象。
//.....解析值并赋值给你的对象
}
如果要实现完成自动解析就得反射了。
以上回答你满意么?

❺ java 解析json字符串

你好:

后台拆分json

privateStringinteractPrizeAll;//json使用字符串来接收
方法中的代码:
Gsongson=newGson();
InteractPrizeinteractPrize=newInteractPrize();
//gson用泛型转List数组多个对象
List<InteractPrize>interactPrizeList=gson.fromJson(interactPrizeAll,newTypeToken<List<InteractPrize>>(){}.getType());//TypeToken,它是gson提供的数据类型转换器,可以支持各种数据集合类型转换
for(inti=0;i<interactPrizeList.size();i++)
{
interactPrize=interactPrizeList.get(i);//获取每一个对象
}
这一种方法是转单个对象时使用的
//gson转对象单个对象
//interactPrize=gson.fromJso(interactPrizeAll,InteractPrize.class);

这个方法是我后台拼的json往前台传的方法
jsonStrAll.append("{"+"""+"catid"+"""+":"+"""+c.getCatid()+"""+","+"""+"catname"+"""+":"+"""+c.getCatname()+"""+","+"""+"catdesc"+"""+":"+"""+c.getCatdesc()+"""+","+"""+"showinnav"+"""+":"+"""+c.getShowinnav()+"""+","+"""+"sortorder"+"""+":"+"""+c.getSortorder()+"""+","+"level:"+"""+"0"+"""+",parent:"+"""+"0"+"""+",isLeaf:true,expanded:false,"+"loaded:true},");

你自己挑着用吧!

❻ java解析json字符串数据

这个需要导入个jar包的,自己写太麻烦,而且要考虑特殊字符的转义的。

1. json-lib是一个java类库,提供将Java对象,包括beans, maps, collections, java arrays and XML等转换成JSON,或者反向转换的功能。

2. json-lib 主页 :http://json-lib.sourceforge.net/

3.执行环境

需要以下类库支持

jakarta commons-lang 2.5

jakarta commons-beanutils 1.8.0

jakarta commons-collections 3.2.1

jakarta commons-logging 1.1.1

ezmorph 1.0.6

4.功能示例

这里通过JUnit-Case例子给出代码示例



packagecom.mai.json;

importstaticorg.junit.Assert.assertEquals;

importjava.util.ArrayList;
importjava.util.Date;
importjava.util.HashMap;
importjava.util.Iterator;
importjava.util.List;
importjava.util.Map;
importnet.sf.ezmorph.Morpher;
importnet.sf.ezmorph.MorpherRegistry;
importnet.sf.ezmorph.bean.BeanMorpher;
importnet.sf.json.JSONArray;
importnet.sf.json.JSONObject;
importnet.sf.json.util.JSONUtils;

importorg.apache.commons.beanutils.PropertyUtils;
importorg.junit.Test;

publicclassJsonLibTest{

/*
*普通类型、List、Collection等都是用JSONArray解析
*
*Map、自定义类型是用JSONObject解析
*可以将Map理解成一个对象,里面的key/value对可以理解成对象的属性/属性值
*即{key1:value1,key2,value2......}
*
*1.JSONObject是一个name:values集合,通过它的get(key)方法取得的是key后对应的value部分(字符串)
*通过它的getJSONObject(key)可以取到一个JSONObject,-->转换成map,
*通过它的getJSONArray(key)可以取到一个JSONArray,
*
*
*/

//一般数组转换成JSON
@Test
publicvoidtestArrayToJSON(){
boolean[]boolArray=newboolean[]{true,false,true};
JSONArrayjsonArray=JSONArray.fromObject(boolArray);
System.out.println(jsonArray);
//prints[true,false,true]
}


//Collection对象转换成JSON
@Test
publicvoidtestListToJSON(){
Listlist=newArrayList();
list.add("first");
list.add("second");
JSONArrayjsonArray=JSONArray.fromObject(list);
System.out.println(jsonArray);
//prints["first","second"]
}


//字符串json转换成json,根据情况是用JSONArray或JSONObject
@Test
publicvoidtestJsonStrToJSON(){
JSONArrayjsonArray=JSONArray.fromObject("['json','is','easy']");
System.out.println(jsonArray);
//prints["json","is","easy"]
}


//Map转换成json,是用jsonObject
@Test
publicvoidtestMapToJSON(){
Mapmap=newHashMap();
map.put("name","json");
map.put("bool",Boolean.TRUE);
map.put("int",newInteger(1));
map.put("arr",newString[]{"a","b"});
map.put("func","function(i){returnthis.arr[i];}");

JSONObjectjsonObject=JSONObject.fromObject(map);
System.out.println(jsonObject);
}

//复合类型bean转成成json
@Test
publicvoidtestBeadToJSON(){
MyBeanbean=newMyBean();
bean.setId("001");
bean.setName("银行卡");
bean.setDate(newDate());

ListcardNum=newArrayList();
cardNum.add("农行");
cardNum.add("工行");
cardNum.add("建行");
cardNum.add(newPerson("test"));

bean.setCardNum(cardNum);

JSONObjectjsonObject=JSONObject.fromObject(bean);
System.out.println(jsonObject);

}

//普通类型的json转换成对象
@Test
publicvoidtestJSONToObject()throwsException{
Stringjson="{name="json",bool:true,int:1,double:2.2,func:function(a){returna;},array:[1,2]}";
JSONObjectjsonObject=JSONObject.fromObject(json);
System.out.println(jsonObject);
Objectbean=JSONObject.toBean(jsonObject);
assertEquals(jsonObject.get("name"),PropertyUtils.getProperty(bean,"name"));
assertEquals(jsonObject.get("bool"),PropertyUtils.getProperty(bean,"bool"));
assertEquals(jsonObject.get("int"),PropertyUtils.getProperty(bean,"int"));
assertEquals(jsonObject.get("double"),PropertyUtils.getProperty(bean,"double"));
assertEquals(jsonObject.get("func"),PropertyUtils.getProperty(bean,"func"));
System.out.println(PropertyUtils.getProperty(bean,"name"));
System.out.println(PropertyUtils.getProperty(bean,"bool"));
System.out.println(PropertyUtils.getProperty(bean,"int"));
System.out.println(PropertyUtils.getProperty(bean,"double"));
System.out.println(PropertyUtils.getProperty(bean,"func"));
System.out.println(PropertyUtils.getProperty(bean,"array"));

ListarrayList=(List)JSONArray.toCollection(jsonObject.getJSONArray("array"));
for(Objectobject:arrayList){
System.out.println(object);
}

}


//将json解析成复合类型对象,包含List
@Test
(){
Stringjson="{list:[{name:'test1'},{name:'test2'}],map:{test1:{name:'test1'},test2:{name:'test2'}}}";
//Stringjson="{list:[{name:'test1'},{name:'test2'}]}";
MapclassMap=newHashMap();
classMap.put("list",Person.class);
MyBeanWithPersondiyBean=(MyBeanWithPerson)JSONObject.toBean(JSONObject.fromObject(json),MyBeanWithPerson.class,classMap);
System.out.println(diyBean);

Listlist=diyBean.getList();
for(Objecto:list){
if(oinstanceofPerson){
Personp=(Person)o;
System.out.println(p.getName());
}
}
}


//将json解析成复合类型对象,包含Map
@Test
(){
//把Map看成一个对象
Stringjson="{list:[{name:'test1'},{name:'test2'}],map:{testOne:{name:'test1'},testTwo:{name:'test2'}}}";
MapclassMap=newHashMap();
classMap.put("list",Person.class);
classMap.put("map",Map.class);
//使用暗示,直接将json解析为指定自定义对象,其中List完全解析,Map没有完全解析
MyBeanWithPersondiyBean=(MyBeanWithPerson)JSONObject.toBean(JSONObject.fromObject(json),MyBeanWithPerson.class,classMap);
System.out.println(diyBean);

System.out.println("dothelistrelease");
List<Person>list=diyBean.getList();
for(Persono:list){
Personp=(Person)o;
System.out.println(p.getName());
}

System.out.println("dothemaprelease");

//先往注册器中注册变换器,需要用到ezmorph包中的类
=JSONUtils.getMorpherRegistry();
MorpherdynaMorpher=newBeanMorpher(Person.class,morpherRegistry);
morpherRegistry.registerMorpher(dynaMorpher);


Mapmap=diyBean.getMap();
/*这里的map没进行类型暗示,故按默认的,里面存的为net.sf.ezmorph.bean.MorphDynaBean类型的对象*/
System.out.println(map);
/*输出:
{testOne=net.sf.ezmorph.bean.MorphDynaBean@f73c1[
{name=test1}
],testTwo=net.sf.ezmorph.bean.MorphDynaBean@186c6b2[
{name=test2}
]}
*/
List<Person>output=newArrayList();
for(Iteratori=map.values().iterator();i.hasNext();){
//使用注册器对指定DynaBean进行对象变换
output.add((Person)morpherRegistry.morph(Person.class,i.next()));
}

for(Personp:output){
System.out.println(p.getName());
/*输出:
test1
test2
*/
}

}}

❼ java后台解析json字符串

JSONArray 是json数据格式,它下边包含了jsonObject格式,所以你应该先取jsonObject,如:
for(int z = 0; z < leng; z++){
System.out.println("zzzz"+z);
JSONObject json = jsona.getJSONObject(z);
String name = json.get("name").toString;
}

你的jsonarray格式要是正确的话就应该可以拿到name值。

❽ 关于Java处理JSON字符串的新手问题

第一点:你既然使用了net.sf.json.JSONObject对象引入了jar包直接使用其的fromObject将对象转为字符串闹档效率更高,出错的概率也更小一些。

第二点:对象中套对象的方式也很简单,稿如如这样

public static void main(String[] args) {

Map map1 = new HashMap();
Map map2 = new HashMap();
Map map3 = new HashMap();

map3.put("value","Male");
map2.put("gender",map3);
map1.put("attributes",map2);

JSONObject json = JSONObject.fromObject(map1);
System.out.println(json);
}

热点内容
童编程 发布:2024-05-06 08:44:01 浏览:246
java路径配置文件 发布:2024-05-06 08:43:47 浏览:903
什么软件可以编程 发布:2024-05-06 08:37:37 浏览:46
java字符串转换 发布:2024-05-06 08:37:25 浏览:885
字符串在内存中的存储 发布:2024-05-06 08:33:29 浏览:393
安卓投影仪安装什么点歌软件 发布:2024-05-06 08:33:22 浏览:545
java开源大全 发布:2024-05-06 08:32:26 浏览:33
可以加密的阅读器 发布:2024-05-06 08:31:51 浏览:262
电脑改群晖服务器 发布:2024-05-06 07:57:19 浏览:39
冒险岛忘记服务器了怎么查 发布:2024-05-06 07:53:42 浏览:241