I parser String to JSON using simplejson.
Here my json string.
"{\"Result\":[{\"trxCode\":\"Y\",\"trxMsg\":\"Success\"}],\"Table1\":[{\"TNS_NM\":\"TEST\",\"USR_ID\":\"TESTER\",\"USR_PWD\":\"TEST\",\"DB_IP\":\"TEST_IP\"}]}"
I need to parse this.
So here my code
private static Map<String, Object> convertInputStreamToString(InputStream inputStream) throws IOException
{
Map<String, Object> result = new HashMap<>();
try
{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
StringBuilder sb = new StringBuilder();
while((line = bufferedReader.readLine()) != null)
sb.append(line);
String json = sb.toString();
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(json); // error occur here
result.put("trxMsg", jsonObject);
}
catch (Exception e)
{
result.put("error", e.getMessage());
// java.lang.String cannot be cast to org.json.simple.JSONObject
}
finally
{
inputStream.close();
}
return result;
}
But If I put the string value directly, no error occurs.
JSONObject jsonObject = (JSONObject) parser.parse("{\"Result\":[{\"trxCode\":\"Y\",\"trxMsg\":\"Success\"}],\"Table1\":[{\"TNS_NM\":\"TEST\",\"USR_ID\":\"TESTER\",\"USR_PWD\":\"TEST\",\"DB_IP\":\"TEST_IP\"}]}");
Even, It work.
String json = "{\"Result\":[{\"trxCode\":\"Y\",\"trxMsg\":\"Success\"}],\"Table1\":[{\"TNS_NM\":\"TEST\",\"USR_ID\":\"TESTER\",\"USR_PWD\":\"TEST\",\"DB_IP\":\"TEST_IP\"}]}";
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(json);
But these not work..
String json = sb.toString();
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(json);
// or...
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(sb.toString());
I know my question is same this.
But that answer can't apply to my code.
Answer is parse in Main.
public static void main(String[] args) { }
But my case, connect is done by the user's button click.
So I cannot be used, and I need for android
I couldn't find a answer anywhere else.
please help me.