Using Google GSON to convert String to JSON Array - java

I am using the Google GSON library to convert an ArrayList of countries into JSON:
ArrayList<String> countries = new ArrayList<String>();
// arraylist gts populated
Gson gson = new Gson();
String json = gson.toJson(countries);
Which yields:
["AFGHANISTAN","ALBANIA","ALGERIA","ANDORRA","ANGOLA","ANGUILLA","ANTARCTICA","ANTIGUA AND BARBUDA","ARGENTINA","ARMENIA","ARUBA","ASHMORE AND CARTIER ISLANDS","AUSTRALIA","AUSTRIA","AZERBAIJAN"]
How can I modify my code to generate a JSON Array? For example:
[
{
"AFGHANISTAN",
"ALBANIA",
"ALGERIA",
"ANDORRA",
"ANGOLA",
"ANGUILLA",
"ANTARCTICA",
"ANTIGUA AND BARBUDA",
"ARGENTINA",
"ARMENIA",
"ARUBA",
"ASHMORE AND CARTIER ISLANDS",
"AUSTRALIA",
"AUSTRIA",
"AZERBAIJAN"
}
]
Thanks!
Here is the code that my Java client uses to parse web service responses that already contain the curly-braces. This is why I want the countries response to contain the curly braces:
Gson gson = new GsonBuilder().create();
ArrayList<Map<String, String>> myList = gson.fromJson(result,
new TypeToken<ArrayList<HashMap<String, String>>>() {
}.getType());
List<Values> list = new ArrayList<Values>();
for (Map<String, String> m : myList) {
list.add(new Values(m.get(attribute)));
}

To build the string you show us, which isn't JSON at all, you may do this :
StringBuilder sb = new StringBuilder("[{");
for (int i=0; i<countries.size(); i++) {
sb.append("\"").append(countries.get(i)).append("\"");
if (i<countries.size()-1) sb.append(",");
}
sb.append("}]");
String theString = sb.toString();
I'd recommend not trying to use Gson, which is only dedicated to JSON.

Using curly-braces is not a "style", it is how JSON denotes an object. square brackets represent a list, and curly-braces are used to represent an object, which in Javascript behaves like a map. Putting curly braces around the list entries is nonsensical because within the object you need name-value pairs (just like a map).

A simple text-representation of an array in JSON is exactly what Gson returns. What for do you need that curly-braces style?

Related

How do I tokenize array of json objects?

Hi I need to tokenize an array of json objects but I'm not sure how to go about doing that.
Currently, I have this snippet:
StringTokenizer tokenizer = new StringTokenizer(request, "{}:,\"");
Map<String, String> properties = new HashMap<String, String>();
while(tokenizer.hasMoreTokens()) {
String key = tokenizer.nextToken();
String value = tokenizer.nextToken();
properties.put(key, value);
}
This snippet allows me to tokenize a regular (non-complex) json object so that I can get the value using the key as the lookup. However, it does not work for complex objects in the form like [{"Foo":"Bar", "XYZ":12}, {"ABC":16, "Foo": "Bar"}...]
So I was wondering how can I tokenize an array of json objects?
Regex is not suitable for parsing or tokenizing JSON. Instead parse JSON with a parser e.g. Gson:
String json = "[{\"Foo\":\"Bar\", \"XYZ\":12}, {\"ABC\":16, \"Foo\": \"Bar\"}]";
Map<String, String>[] result = new Gson().fromJson(json, new TypeToken<Map<String, String>[]>() {}.getType());
System.out.println(Arrays.toString(result));
will output below showing two Map objects:
[{Foo=Bar, XYZ=12}, {ABC=16, Foo=Bar}]

Value as string array in gson key value

I'm new to JSON. I'm trying to assign value (in key value pairs) as array of strings using GSON.
The JSON should look like as below:
{ "name": "path", "value": [ "/my-path" ,"/my-path2","/newpath"] }
How can I achieve this?
Thanks.
Even thoe I will hardly recommend you to use POJOS, gson is flexible enough to allow you to do what you want:
JsonObject jo = new JsonObject();
jo.addProperty("name", "path");
JsonArray jsonArray = new JsonArray();
jsonArray.add("my-path");
jsonArray.add("my-path2");
jsonArray.add("my-new-path");
jo.add("value", jsonArray);
System.out.println(jo);

How to convert JSON to HashMap and compare them?

I have a json stored in a DB like this,
"supported_iso_codes":[
{
"EUR": "978",
"USD": "840"
}
],
To access this in my app code, I do something like this..
getISOProfileDB.getSupportedISOCodes();
I have a string which the user inputs(provides input string like EUR, USD,etc). How can I convert the above json to a HashMap and compare it with another string? What I am trying to achieve is,
Compare Key part of json to user input string(EUR).
If both of them match,
Parse the value part of json and store it in a variable.
Below is what I'm trying to achieve,
tran.setCurrency(hashMapOfJson.get(currencyString));
Use Gson :
dependencies {
compile 'com.google.code.gson:gson:2.2.4'
}
And then :
Map<String, Object> supported_iso_codes = new Gson().fromJson(getISOProfileDB.getSupportedISOCodes(), new TypeToken<HashMap<String, Object>>() {}.getType());
You can do something like this
Gson gson = new Gson();
Type type = new TypeToken<List<Map<String, String>>>(){}.getType();
final ArrayList<HashMap<String,String>> isoCodesMapList = gson.fromJson(data, type);
System.out.println(arrayList);
then for getting the user selected currency you can do
isoCodesMapList.get(userSelectedCurrency);
Hope this helps:)
You should consider using JSONObject (Jsonobject.org) or Gson.

Gson to get Json value for a pie chart using Highcharts

I am working on Pie Charts using HighCharts.
The structure of JSON i needed is
data: [
['Firefox', 45.0],
['IE', 26.8],
['Safari', 8.5],
['Opera', 6.2],
['Others', 0.7]
]
I am using GSON to convert this into JSON object.
I tried to add a class 'Browser' which contains
private List browserName = new ArrayList();
private List browserValue = new ArrayList();
// passing the browser class object to Gson
gson.toJson(browser);
In graph I passed the data as
data: [
json.browserName,json.browserValue
]
But this didnt worked. How can I achieve the required JSON format when name and value is a list.
I added some quotes and braces to make your json valid. Then, it's a matter of looping through your data key which gives you an array of arrays.
String jsonString =
"{'data':[['Firefox',45.0],['IE',26.8],['Safari',8.5],['Opera',6.2],['Others',0.7]]}";
JsonParser parser = new JsonParser();
JsonObject jsonObject = parser.parse(jsonString).getAsJsonObject();
JsonArray data = jsonObject.get("data").getAsJsonArray();
for(int i = 0; i < data.size(); i++) {
JsonArray dataIndex = data.get(i).getAsJsonArray();
System.out.println(dataIndex.get(0));
System.out.println(dataIndex.get(1));
}
I find it helps me to visualize the json before writing code to go in and get values.

How to convert List to a JSON Object using GSON?

I have a List which I need to convert into JSON Object using GSON. My JSON Object has JSON Array in it.
public class DataResponse {
private List<ClientResponse> apps;
// getters and setters
public static class ClientResponse {
private double mean;
private double deviation;
private int code;
private String pack;
private int version;
// getters and setters
}
}
Below is my code in which I need to convert my List to JSON Object which has JSON Array in it -
public void marshal(Object response) {
List<DataResponse.ClientResponse> clientResponse = ((DataResponse) response).getClientResponse();
// now how do I convert clientResponse list to JSON Object which has JSON Array in it using GSON?
// String jsonObject = ??
}
As of now, I only have two items in List - So I need my JSON Object like this -
{
"apps":[
{
"mean":1.2,
"deviation":1.3
"code":100,
"pack":"hello",
"version":1
},
{
"mean":1.5,
"deviation":1.1
"code":200,
"pack":"world",
"version":2
}
]
}
What is the best way to do this?
There is a sample from google gson documentation on how to actually convert the list to json string:
Type listType = new TypeToken<List<String>>() {}.getType();
List<String> target = new LinkedList<String>();
target.add("blah");
Gson gson = new Gson();
String json = gson.toJson(target, listType);
List<String> target2 = gson.fromJson(json, listType);
You need to set the type of list in toJson method and pass the list object to convert it to json string or vice versa.
If response in your marshal method is a DataResponse, then that's what you should be serializing.
Gson gson = new Gson();
gson.toJson(response);
That will give you the JSON output you are looking for.
Assuming you also want to get json in format
{
"apps": [
{
"mean": 1.2,
"deviation": 1.3,
"code": 100,
"pack": "hello",
"version": 1
},
{
"mean": 1.5,
"deviation": 1.1,
"code": 200,
"pack": "world",
"version": 2
}
]
}
instead of
{"apps":[{"mean":1.2,"deviation":1.3,"code":100,"pack":"hello","version":1},{"mean":1.5,"deviation":1.1,"code":200,"pack":"world","version":2}]}
you can use pretty printing. To do so use
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(dataResponse);
Make sure to convert your collection to Array:
Gson().toJson(objectsList.toTypedArray(), Array<CustomObject>::class.java)
We can also use another workaround by first creating an array of myObject then convert them into list.
final Optional<List<MyObject>> sortInput = Optional.ofNullable(jsonArgument)
.map(jsonArgument -> GSON.toJson(jsonArgument, ArrayList.class))
.map(gson -> GSON.fromJson(gson, MyObject[].class))
.map(myObjectArray -> Arrays.asList(myObjectArray));
Benifits:
we are not using reflection here. :)

Categories

Resources