我在Java中创建一个JSON:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.gson.Gson;
String json = null;
Map<String, String> data1 = new HashMap<String, String>();
Map<String, String> data2 = new HashMap<String, String>();
data1.put("name", "f1");
data1.put("key", "aa1");
data1.put("value", "21");
data2.put("name", "f2");
data2.put("key", "aa1");
data2.put("value", "22");
JSONObject json1 = new JSONObject(data1);
JSONObject json2 = new JSONObject(data2);
JSONArray array = new JSONArray();
array.put(json1);
array.put(json2);
JSONObject finalObject = new JSONObject();
try {
finalObject.put("DeltaRealTime", array);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
json = new Gson().toJson(finalObject);
我得到的是以下内容:
{
"map": {
"DeltaRealTime": {
"myArrayList": [{
"map": {
"name": "f1",
"value": "21",
"key": "aa1"
}
}, {
"map": {
"name": "f2",
"value": "22",
"key": "aa1"
}
}]
}
}
}
但我不想让所有这些额外的&#34; map&#34;节点。我该怎么做才能删除它们?或者我能做什么呢?我首先没有它们?
答案 0 :(得分:1)
要简单地将JSONObject转换为String,您可以使用toString()meethod。我没有使用Gson Library就做了同样的事情,我没有得到任何地图节点。
import java.util.HashMap;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class checkTimeStamp {
public static void main(String[] args){
Map<String, String> data1 = new HashMap<String, String>();
Map<String, String> data2 = new HashMap<String, String>();
data1.put("Hello", "abc");
data1.put("Hello1", "abc");
data1.put("Hello2", "abc");
data2.put("Hello", "abc");
data2.put("Hello1", "abc");
data2.put("Hello2", "abc");
JSONObject json1 = new JSONObject(data1);
JSONObject json2 = new JSONObject(data2);
JSONArray array = new JSONArray();
array.put(json1);
array.put(json2);
JSONObject finalObj = new JSONObject();
try{
finalObj.put("RealTimeData", array);
}
catch(JSONException e){
e.printStackTrace();
}
String json = finalObj.toString();
System.out.println(json);
}
}
输出是:
{"RealTimeData":[{"Hello1":"abc","Hello2":"abc","Hello":"abc"},{"Hello1":"abc","Hello2":"abc","Hello":"abc"}]}
答案 1 :(得分:0)
我建议使用像Jackson这样的Object to JSON字符串转换器库。你可以通过三个简单的步骤获得json str,而不必创建任何JSON对象:
<强>步骤强>
使用以下方法将对象转换为JSON字符串:
ObjectMapper mapper = new ObjectMapper();
mapper.writeValueAsString(FooPOJO);
参考:http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/