Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't Convert string to JsonArray

Tags:

How do you convert this String into gson.JsonArray?

String s= "[["110917    ", 3.0099999999999998, -0.72999999999999998, 2.8500000000000001, 2.96, 685.0, 38603.0], ["110917    ", 2.71, 0.20999999999999999, 2.8199999999999998, 2.8999999999999999, 2987.0, 33762.0]]"; 

This is my Code:

 com.google.gson.*;  public static void main(String[] args)    {        //Declared S here        System.out.println("String to Json Array Stmt");        JsonParser parser = new JsonParser();        JsonElement tradeElement = parser.parse(s.toString());        JsonArray trade = tradeElement.getAsJsonArray();        System.out.println(trade);     } 

Is this the way to convert this Collections string to JSonArray?

like image 859
Nava Avatar asked Jun 23 '11 13:06

Nava


People also ask

How do you convert a string to a JSON object in Python?

Use the json.loads() function. The json. loads() function accepts as input a valid string and converts it to a Python dictionary. This process is called deserialization – the act of converting a string to an object.

Can we convert JSONArray to JSONObject?

Core Java bootcamp program with Hands on practiceWe can also add a JSONArray to JSONObject. We need to add a few items to an ArrayList first and pass this list to the put() method of JSONArray class and finally add this array to JSONObject using the put() method.


1 Answers

To have a string value inside your JSON array, you must remember to backslash escape your double-quotes in your Java program. See the declaration of s below.

String s = "[[\"110917       \", 3.0099999999999998, -0.72999999999999998, 2.8500000000000001, 2.96, 685.0, 38603.0], [\"110917    \", 2.71, 0.20999999999999999, 2.8199999999999998, 2.8999999999999999, 2987.0, 33762.0]]"; 

Your code in the main() method works fine. Below is just a minor modification of your code in the main() method.

System.out.println("String to Json Array Stmt"); JsonParser parser = new JsonParser(); JsonElement tradeElement = parser.parse(s); JsonArray trade = tradeElement.getAsJsonArray(); System.out.println(trade); 

Lastly, remember to prefix your statement "com.google.gson.*" with the keyword "import", as shown below.

import com.google.gson.*; 
like image 98
AaronYC Avatar answered Sep 29 '22 20:09

AaronYC