详解java生成json字符串的方法
程序员文章站
2024-03-08 10:19:10
例1:将map对象添加一次元素(包括字符串对、数组),转换成json对象一次。
代码:
package com.json;
//这是使用org.js...
例1:将map对象添加一次元素(包括字符串对、数组),转换成json对象一次。
代码:
package com.json; //这是使用org.json的程序: import java.util.hashmap; import java.util.map; import org.json.jsonexception; import org.json.jsonobject; public class jsontest { public static void main(string[] args) throws jsonexception { string json = "{'name':'reiz'}"; jsonobject jsonobj = new jsonobject(json); string name = jsonobj.getstring("name"); system.out.println(jsonobj); jsonobj.put("initial", name.substring(0, 1).touppercase()); string[] likes = new string[] { "javascript", "skiing", "apple pie" }; jsonobj.put("likes", likes); system.out.println(jsonobj); map <string, string> ingredients = new hashmap <string, string>(); ingredients.put("apples", "3kg"); ingredients.put("sugar", "1kg"); ingredients.put("pastry", "2.4kg"); ingredients.put("besteaten", "outdoors"); jsonobj.put("ingredients", ingredients); system.out.println(jsonobj); } }
运行结果:
{"name":"reiz"} {"initial":"r","likes":["javascript","skiing","apple pie"],"name":"reiz"} {"ingredients":{"apples":"3kg","pastry":"2.4kg","besteaten":"outdoors","sugar":"1kg"},"initial":"r","likes":["javascript","skiing","apple pie"],"name":"reiz"}
(需要用到的包可在官网下载:)
例2:list转换成json的三种参数形式。
import java.util.arraylist; import java.util.list; import net.sf.json.jsonarray; import net.sf.json.jsonobject; public class listtojson { public static void main(string[] args) { boolean[] boolarray = new boolean[]{true,false,true}; jsonarray jsonarray1 = jsonarray.fromobject( boolarray ); system.out.println( jsonarray1 ); // prints [true,false,true] list list = new arraylist(); list.add( "first" ); list.add( "second" ); jsonarray jsonarray2 = jsonarray.fromobject( list ); system.out.println( jsonarray2 ); // prints ["first","second"] jsonarray jsonarray3 = jsonarray.fromobject( "['json','is','easy']" ); system.out.println( jsonarray3 ); // prints ["json","is","easy"] } }
运行结果:
[true,false,true] ["first","second"] ["json","is","easy"]
例3:json转换成list和map。
package com.json; import java.util.collection; import java.util.map; import java.util.map.entry; import net.sf.json.jsonarray; import net.sf.json.jsonobject; public class jsontolistandmap { public static void main(string[] args) { // todo auto-generated method stub string liststr = "[\"apple\",\"orange\"]"; collection<string> strlist = jsonarray.tocollection(jsonarray.fromobject(liststr)); for (string str : strlist) { system.out.println(str); } string mapstr = "{\"age\":30,\"name\":\"michael\",\"baby\":[\"lucy\",\"lily\"]}"; map<string, object> map = (map) jsonobject.tobean(jsonobject .fromobject(mapstr), map.class); for (entry<string, object> entry : map.entryset()) { system.out.println(entry.getkey() + " " + entry.getvalue()); } } }
运行结果:
apple
orange
name michael
age 30
baby [lucy, lily]
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: Java实现简单树结构