0

我正在尝试“创建”一个 JSONObject。现在我正在使用 JSON-Simple,我正在尝试按照这个思路做一些事情(对不起,如果这个示例 JSON 文件中有任何错字)

{
    "valuedata": {
        "period": 1,
        "icon": "pretty"
    }
}

现在我在寻找如何通过 Java 将 valuedata 写入 JSON 文件时遇到问题,我尝试的是:

Map<String, String> t = new HashMap<String, String>();
t.put("Testing", "testing");
JSONObject jsonObject = new JSONObject(t);

但这只是

{
    "Testing": "testing"
}
4

2 回答 2

0

您想要做的是将另一个 JSONObject 放入您的 JSONObject“jsonObject”中,更准确地说是在“valuedata”字段中。你可以那样做...

// 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.
于 2015-03-28T07:13:07.283 回答
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"}

于 2015-03-28T07:23:16.477 回答