如何在json对象中创建数组

时间:2019-03-11 09:41:08

标签: 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 = 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数字的双引号的更多逻辑,因为考虑到字符串,因为这两个数字均应为Expected中提到的数组格式。

5 个答案:

答案 0 :(得分:1)

替换行

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

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

答案 1 :(得分:1)

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

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

如果要创建一个josn数组节点,则显示使用JSONArray,并使用JSONArray#put(*)方法添加元素。

将字符串放入JSONArrayJSONObject中,不需要用quote(“)包装字符串。此外,您应该写\"而不是(char) 34在Java中有点晦涩。


以下情况用于回复评论。

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

答案 2 :(得分:0)

您的值是'to'的字符串,因此可以将json转换为数组后再将字符串转换为json吗?

答案 3 :(得分:0)

这是您所需的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"] 

答案 4 :(得分:0)

替换

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

使用

jsonObj.put("to",arrayNumbers);