字符串到JSONArray由于字符串中的斜杠而导致异常 [英] String to JSONArray giving exception because of slash in string

查看:833
本文介绍了字符串到JSONArray由于字符串中的斜杠而导致异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将json字符串转换为的JSONArray org.json.JSONArray类,该字符串包含带有正向slah的dateformat,但是由于字符串中包含斜杠,所以出现了以下异常.

I am trying to convert a json string to JSONArray of org.json.JSONArray class, the string contains a dateformat with forward slah, but I am getting the following exception because of the slash included in string.

public static void main(String args[]) throws JSONException{

        String jsonString = "[{ID:1, Name:Ann, DOB:14/08/1991}, {ID:2, Name:Vann, DOB:14/08/1992}]";
        JSONArray jsonArray = new JSONArray(jsonString);
        System.out.println(jsonArray.toString());
    }

Exception in thread "main" org.json.JSONException: Expected a ',' or '}' at 25 [character 26 line 1]
    at org.json.JSONTokener.syntaxError(JSONTokener.java:451)
    at org.json.JSONObject.<init>(JSONObject.java:230)
    at org.json.JSONTokener.nextValue(JSONTokener.java:380)
    at org.json.JSONArray.<init>(JSONArray.java:118)
    at org.json.JSONArray.<init>(JSONArray.java:147)
    at com.s4m.sftp.service.impl.SFTPServiceImpl.main(SFTPServiceImpl.java:1150)

推荐答案

JSON中的字符串值

字符串应加引号...,包括属性名称.参见 JSON规范:

对象结构表示为一对大括号,包围着零个或多个名称/值对(或成员).名称是字符串.

An object structure is represented as a pair of curly brackets surrounding zero or more name/value pairs (or members). A name is a string.

字符串的表示类似于C系列编程语言中使用的约定.字符串以引号开头和结尾.

The representation of strings is similar to conventions used in the C family of programming languages. A string begins and ends with quotation marks.

JSON中的日期值

JSON不代表date类型.它必须表示为字符串.有关更多信息,请参见此答案.

Date values in JSON

JSON has no representation for date type. It must be represented as a string. See this answer for more information.

您可以使用在线JSON验证器来检查其有效性.

You can use online JSON validators to check the validity.

[
   {
      "ID":1,
      "Name":"Ann",
      "DOB":"14/08/1991"
   },
   {
      "ID":2,
      "Name":"Vann",
      "DOB":"14/08/1992"
   }
]

但是,我将格式yyyy-mm-dd用于日期值而不是dd/mm/yyyy.

However, I would use the format yyyy-mm-dd for date values instead of dd/mm/yyyy.

String jsonString =
"[{\"ID\":1,\"Name\":\"Ann\",\"DOB\":\"14/08/1991\"},{\"ID\":2,\"Name\":\"Vann\",\"DOB\":\"14/08/1992\"}]";

这篇关于字符串到JSONArray由于字符串中的斜杠而导致异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆