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.
Related
I am using the JSONArray object and I am passing to the constructor of that object a string. The string that I'm passing is
[{\"x\":18.4300,\"y\":30.4700,\"w\":53.0900,\"fontSize\": 11,\"bold\": 0,\"charcount\": 22,\"id\": 349133}].
After out-printing the json object, I get the following:
[{"charcount":22,"w":53.09,"x":18.43,"y":30.47,"fontSize":11,"bold":0,"id":349133}].
Can I get an example in code of how I can preserve the order of the original json string?
You can use a an ordered collection to parse your json to keep it's order.
A sample for your json:
String json = "[{\"x\":18.4300,\"y\":30.4700,\"w\":53.0900,\"fontSize\": 11,\"bold\": 0,\"charcount\": 22,\"id\": 349133}]";
Gson gson = new Gson();
Type type = new TypeToken<Set<LinkedTreeMap<String, Object>>>() {}.getType();
Set<LinkedTreeMap<String, Object>> myMap = gson.fromJson(json, type);
System.out.println(json);
System.out.println(myMap);
Using GSON :
Gson gson = new Gson();
String json = gson.toJson(response);
System.out.println(json);
I receive the following JSON representation of a User:
"{\"userID\":\"user2\",\"firstName\":\"Maria\",\"lastName\":\"Silva\",\"birthDate\":\"Ago 1, 2012\",\"gender\":\"Female\"}"
Now, I want to get those values to construct a User object (doing User.setuserID, userObj.setFirstName, ... )
How can I get the correspond values to set the User values?
Gson will do that for you. You need not worry about it. That's the power of Gson.
User object = gson.fromJson(jsonString, User.class); // Fully populated User object.
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?
I would like to know if it is possible to convert any Java object to JSON object. Currently I have the following code.
JSONArray data = new JSONArray();
for (User user : users) {
JSONArray row = new JSONArray();
row.put(user.getId()).put(user.getUserName()).put(user.isEnabled());
data.put(row);
}
The current issue is different object (e.g. User and Admin) will have different property, thus the above code will work for other object. I am thinking of putting a similar code in my GenericHibernateDAO in order to automatically convert any list into a json list.
You can serialize your java object to json object. There are n number of library is available ex gson, jettyson, flexjson etc.
GSON example -
Gson gson = new Gson();
Collection<Integer> ints = Lists.immutableList(1,2,3,4,5);
(Serialization)
String json = gson.toJson(ints); ==> json is [1,2,3,4,5]
Here i exemplify the way of converting POJO to json using jackson
create your pojo : User user = new User();
you can set or get values to/from user
create ObjectMapper : ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(user);// object to json
I'm not very familiar with Java, but got the job to reverse the following JSON-Output to a JAVA object-structure:
Sample:
{"MS":["FRA",56.12,11.67,"BUY"],"DELL":["MUC",54.76,9.07,"SELL"]}
Does someone know, how to build the Arrays / Objetcs and the code to read the strings with Java? JSON or GSON codesamples are welcome.
Thanks!
You could try something like:
Gson gson = new Gson();
Type type = new TypeToken<HashMap<String, String>>(){}.getType();
HashMap<String, String> map = new HashMap<String, String>();
map = gson.fromJson( json, type );
Where "json" is the json string you defined.
Jackson library is most commonly used to parse JSON in Java. Forget about regular expressions and parsing by hand, this is more complicated than you might think. It all boils down to:
String json = "{\"MS\":[\"FRA\",56.12,11.67,\"BUY\"],\"DELL\":[\"MUC\",54.76,9.07,\"SELL\"]}";
ObjectMapper mapper = new ObjectMapper();
Map obj = mapper.readValue(json, Map.class);
You can also map directly to Java beans.