Java 如何在json对象中创建数组

Java 如何在json对象中创建数组,java,arrays,json,Java,Arrays,Json,我用的是这样的东西- String Number1=to_1; String Number2=to_2; String[] arrayNumbers = new String[] {(char)34+Number1+(char)34,(char)34+Number2+(char)34}; System.out.println(Arrays.toString(arrayNumbers)); JSONObject jsonObj = n

我用的是这样的东西-

String Number1=to_1;
        String Number2=to_2;
        String[] arrayNumbers = new String[] {(char)34+Number1+(char)34,(char)34+Number2+(char)34};
        System.out.println(Arrays.toString(arrayNumbers));
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("to",Arrays.toString(arrayNumbers));
        jsonObj.put("type",type);
        jsonObj.put("callback",callbackUrl);
        JSONArray array = new JSONArray();
        JSONObject Array_item = new JSONObject();
        jsonObj.put(type, array);
        Array_item.put("caption",captionName);
        array.add(Array_item);

        System.out.println(jsonObj.toString());
预期-

{
  "to":["91890xx", "91890xx"],
 "type": "document", "document" : {"caption" : "doc"},
"callback":"{{callback}}"
}
实际-
{“document”:[{“caption”:“hello”}],“callback”:“{{callback}}”,“to”:“[\“91890xxx\”,\“91890xx\”],“type”:“document”}


我不知道还有什么逻辑可以删除to number where的out双引号,因为它考虑到to一个字符串,其中两个数字都应该是预期中提到的数组格式。

您的值是字符串“to”,因此您可以将字符串转换为json,然后再将json转换为数组

这正是您所需的json的结构

 {
        "to": ["91890xx", "91890xx"],
        "type": "document",
        "document": {
            "caption": "doc"
        },
        "callback": "{{callback}}"
    }
要删除双引号,请使用如下所示的替换功能

String  Number1="[\"91890xxx\", \"91890xx\"]";
        Number1.replace("\\/", "");
        System.out.println("Excepted output:"+Number1);
output:

Excepted output:["91890xxx", "91890xx"] 
替换

jsonObj.put("to",Arrays.toString(arrayNumbers));

换行

jsonObj.put(“to”,Arrays.toString(arrayNumbers))


jsonObj.put(“to”,Arrays.asList(arrayNumbers))

首先,我向您展示正确的代码:

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Test {
  /**
   * <pre>
   *  {
   *    "to":["91890xx", "91890xx"],
   *    "type": "document",
   *    "document" : {"caption" : "doc"},
   *    "callback":"{{callback}}"
   *  }
   * </pre>
   *
   * @param args
   * @throws JSONException
   */
   public static void main(String[] args) throws JSONException {
    String number1 = "91890";
    String number2 = "91890";
    String[] numbers = new String[]{number1, number2};

    JSONArray toNode = new JSONArray();
    for (String number : numbers) {
      toNode.put(number);
    }

    JSONObject jsonObj = new JSONObject();
    jsonObj.put("to", toNode);
    jsonObj.put("type", "document");
    jsonObj.put("document", new JSONObject().put("caption", "doc"));
    jsonObj.put("callback", "{{callback}}");

    System.out.println(jsonObj.toString());
  }
}
如果要创建josn数组节点,可以显示use
JSONArray
,并使用
JSONArray\put(*)
方法添加元素

将字符串放入
JSONArray
JSONObject
,您不需要用引号(“)来包装字符串。此外,您应该编写
\”
,而不是
(char)34
,这在Java中有点晦涩


以下案例用于回复评论

{"key1":"value1","key2":"Thu Mar 14 20:20:49 CST 2019","key5":{"key5-key1":"value"},"key6":[1,2,3,4],"key3":1,"key9":"A","key7":10,"key8":["a","b","c"],"key10":["A","B","C"]}

为什么不只使用jsonObj.put(“to”,new JSONArray().put(“”)。put(“”)?我有一个问题,如果我需要将相同的函数也用于一个数字,该怎么办。因为这看起来像是硬编码的。你可以定义一个函数来实现这一点。函数的参数可以是map和list/array。使用JSONObject处理映射,使用JSONArray处理列表/数组。这些函数应该使用递归算法。你能用一个例子来解释吗?你真是个天才。谢谢
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Test {
  /**
   * <pre>
   *  {
   *    "to":["91890xx", "91890xx"],
   *    "type": "document",
   *    "document" : {"caption" : "doc"},
   *    "callback":"{{callback}}"
   *  }
   * </pre>
   *
   * @param args
   * @throws JSONException
   */
   public static void main(String[] args) throws JSONException {
    String number1 = "91890";
    String number2 = "91890";
    String[] numbers = new String[]{number1, number2};

    JSONArray toNode = new JSONArray();
    for (String number : numbers) {
      toNode.put(number);
    }

    JSONObject jsonObj = new JSONObject();
    jsonObj.put("to", toNode);
    jsonObj.put("type", "document");
    jsonObj.put("document", new JSONObject().put("caption", "doc"));
    jsonObj.put("callback", "{{callback}}");

    System.out.println(jsonObj.toString());
  }
}
{"document":{"caption":"doc"},"callback":"{{callback}}","to":["91890","91890"],"type":"document"}
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.net.URI;
import java.net.URL;
import java.util.*;

public class Test1 {

  public static void main(String[] args) throws JSONException {
    Map<String, Object> map = new HashMap<>();
    map.put("key1", "value1");
    map.put("key2", new Date());
    map.put("key3", 1);
    map.put("key4", null);
    map.put("key5", Collections.singletonMap("key5-key1", "value"));
    map.put("key6", Arrays.asList(1, 2, 3, 4));
    map.put("key7", BigDecimal.TEN);
    map.put("key8", new String[]{"a", "b", "c"});
    map.put("key9", TestEnum.A);
    map.put("key10", new TestEnum[]{TestEnum.A, TestEnum.B, TestEnum.C});

    Object json = buildJsonObj(map);
    System.out.println(json);
  }

  private static Object buildJsonObj(Object source) throws JSONException {
    if (source == null) {
      return null;
    }
    if (isSimpleValueType(source.getClass())) {
      return source;
    }

    if (source instanceof Map) {
      Map<Object, Object> map = (Map<Object, Object>) source;
      JSONObject jsonObject = new JSONObject();
      for (Map.Entry<Object, Object> entry : map.entrySet()) {
        Object key = entry.getKey();
        if (!(key instanceof String)) {
          throw new IllegalArgumentException("key must be string.");
        }
        jsonObject.put((String) key, buildJsonObj(entry.getValue()));
      }
      return jsonObject;
    }
    if (source instanceof Iterable) {
      Iterable<Object> iterable = (Iterable<Object>) source;
      JSONArray jsonArray = new JSONArray();
      for (Object value : iterable) {
        jsonArray.put(buildJsonObj(value));
      }
      return jsonArray;
    }
    if (source.getClass().isArray()) {
      Object[] array = (Object[]) source;
      JSONArray jsonArray = new JSONArray();
      for (Object value : array) {
        jsonArray.put(buildJsonObj(value));
      }
      return jsonArray;
    }

    throw new IllegalArgumentException("Unsupported type: " + source + ".");
  }

  private static boolean isSimpleValueType(Class<?> clazz) {
    return (Enum.class.isAssignableFrom(clazz) ||
        CharSequence.class.isAssignableFrom(clazz) ||
        Number.class.isAssignableFrom(clazz) ||
        Date.class.isAssignableFrom(clazz) ||
        URI.class == clazz || URL.class == clazz ||
        Locale.class == clazz);
  }

  public enum TestEnum {
    A, B, C
  }
}
{"key1":"value1","key2":"Thu Mar 14 20:20:49 CST 2019","key5":{"key5-key1":"value"},"key6":[1,2,3,4],"key3":1,"key9":"A","key7":10,"key8":["a","b","c"],"key10":["A","B","C"]}