详解java生成json字符串的方法

时间:2021-05-19

例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"}

(需要用到的包可在官网下载:http://.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]

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章