我试图"创建"一个JSONObject。现在我正在使用JSON-Simple,我试图按照这一点做一些事情(对不起,如果在这个示例JSON文件中做了任何拼写错误)
{
"valuedata": {
"period": 1,
"icon": "pretty"
}
}
现在我在查找如何通过Java将valuata写入JSON文件时遇到问题,我尝试的是:
Map<String, String> t = new HashMap<String, String>();
t.put("Testing", "testing");
JSONObject jsonObject = new JSONObject(t);
但那只是
{
"Testing": "testing"
}
答案 0 :(得分:0)
你要做的就是在你的JSONObject&#34; jsonObject&#34;中放入另一个JSONObject,在字段&#34;有价值的数据&#34;更确切地说。你可以这样做......
// Create empty JSONObect here: "{}"
JSONObject jsonObject = new JSONObject();
// Create another empty JSONObect here: "{}"
JSONObject myValueData = new JSONObject();
// Now put the 2nd JSONObject into the field "valuedata" of the first:
// { "valuedata" : {} }
jsonObject.put("valuedata", myValueData);
// And now add all your fields for your 2nd JSONObject, for example period:
// { "valuedata" : { "period" : 1} }
myValueData.put("period", 1);
// etc.
答案 1 :(得分:0)
Following is example which shows JSON object streaming using Java JSONObject:
import org.json.simple.JSONObject;
class JsonEncodeDemo
{
public static void main(String[] args)
{
JSONObject obj = new JSONObject();
obj.put("name","foo");
obj.put("num",new Integer(100));
obj.put("balance",new Double(1000.21));
obj.put("is_vip",new Boolean(true));
StringWriter out = new StringWriter();
obj.writeJSONString(out);
String jsonText = out.toString();
System.out.print(jsonText);
}
}
While compile and executing above program, this will produce following result:
{"balance": 1000.21, "num":100, "is_vip":true, "name":"foo"}