如何从Java中包含诸如':','['和']'之类的字符的String中创建Json对象 [英] How to create Json object from String containing characters like ':' ,'[' and ']' in Java

查看:136
本文介绍了如何从Java中包含诸如':','['和']'之类的字符的String中创建Json对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,我想从中创建一个jsonobject

I have one string from which I want to create one jsonobject

import org.json.JSONObject;

JSONObject json=new JSONObject("{success=false, errorMessage=Application with appId : [randomAppId] not registered, errorCode=102}");
System.out.println("JSON:"+json.toString());

但是由于字符串之内的:[]之类的字符,我现在遇到了异常.

BUT right now I'm getting exception due to characters like :,[,] which is inside the string.

Stacktrace:

Stacktrace:

Exception in thread "main" org.json.JSONException: Expected a ',' or '}' at character 53
    at org.json.JSONTokener.syntaxError(JSONTokener.java:410)
    at org.json.JSONObject.<init>(JSONObject.java:222)
    at org.json.JSONObject.<init>(JSONObject.java:402)

推荐答案

问题是,您的字符串不是有效的JSON.试试:

The problem is, that your string is not valid JSON. Try:

JSONObject json=new JSONObject("{\"success\":false, \"errorMessage\":\"Application with appId : [randomAppId] not registered\", \"errorCode\":102}");

这篇关于如何从Java中包含诸如':','['和']'之类的字符的String中创建Json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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