Java parse JSON String to array or objectlist - java

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.

Related

How do i preserve the original order of json with JSONArray

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);

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.

toString() changes the curly braces into square?

I have the following construct in my code for the following JSON
SomeVariable =
{
"FirstVar":{
"service1":"value1"
}
}
For this I have the following
code in Java
Map<String,String> internal_service_var = new HashMap<String,String>();
internal_service_endpoint.put("service1","value1");
Map<String, String> first_var = new HashMap<String,String>();
first_var.put("FirstVar", internal_service_var.entrySet().toString());
Map<String, String> some_var = new HashMap<String, String>();
some_var.put("SomeVariable", first_var.entrySet().toString());
Here is how I try to use it in the JSON to send over wire
Note that the value of the property in the JSON needs to be a String
JSONObject json = new JSONObject
json.put("var", some_var);
This sets the 'var' property in the json to be
[SomeVariable = [ "FirstVar":[ "service1":"value1"]]]
Instead of
SomeVariable = { "FirstVar":{ "service1":"value1"}}
What am I missing?
The toString() of HashMap does not return the data in JSON format. If you want JSON objects use only JSONObject.
Alternatively, use xstream:
XStream xstream = new XStream(new JettisonMappedXmlDriver());
xstream.setMode(XStream.NO_REFERENCES);
String jsonRepresentation = map.toXML();
jsonRepresentation will have your json. Yes, for reasons only known to ancient sages, xstream uses toXML for serialization. It's misnamed, and unlikely to change to anything else.

Json: Deserialization error while using Gson library

I have json string that should be converted back to a Map type.
Json used:
String jsonString = "{
"varA": "<math><mrow><mn>8</mn></mrow></math>",
"varB": "<math><mrow><mi>m</mi></mrow></math>",
"ans": "<math><mrow><mn>8</mn><mo>⁢</mo><mi>m</mi></mrow></math>"
}"
Code that converts json to Map:
Map<String, String> variableMap = gson.fromJson(jsonString, new TypeToken<Map<String,String>>(){}.getType());
Error:
[ERROR] The JsonDeserializer StringTypeAdapter failed to deserialize json object {"varA":"<math><mrow><mn>8</mn></mrow></math>","varB":"<math><mrow><mi>m</mi></mrow></math>","ans":"<math><mrow><mn>8</mn><mo>⁢</mo><mi>m</mi></mrow></math>"} given the type class java.lang.String
I know it has something to do with the type, but I have indicated that the type will be String explicitly in the type token.
The gson object is declared as follows:
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
You have to escape the quotes that delimit the JSON string values contained within your Java string. In fact your example is not a valid Java program - Java lacks multi-line strings, for starters.
The following snippet runs just fine (angle brackets and the Unicode character turn out to be innocuous):
public static void main(String[] args) {
String jsonString = "{\"varA\": \"<math><mrow><mn>8</mn></mrow></math>\", \"varB\": \"<math><mrow><mi>m</mi></mrow></math>\", \"ans\": \"<math><mrow><mn>8</mn><mo>⁢</mo><mi>m</mi></mrow></math>\"}";
Map<String, String> variableMap = new Gson().fromJson(jsonString, new TypeToken<Map<String,String>>(){}.getType());
System.out.println("foo");
}
It is working when you use Map.class instead of new TypeToken<Map<String,String>>(){}.getType(). See my little example:
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
Map<String, String> map = new HashMap<String, String>();
map.put("varA", "<math><mrow><mn>8</mn></mrow></math>");
map.put("varB", "<math><mrow><mi>m</mi></mrow></math>");
map.put("ans", "<math><mrow><mn>8</mn><mo>⁢</mo><mi>m</mi></mrow></math>");
String json = gson.toJson(map);
System.out.println(json);
System.out.println(gson.fromJson(json, Map.class));
It prints:
{
"varB":"<math><mrow><mi>m</mi></mrow></math>",
"ans":"<math><mrow><mn>8</mn><mo>⁢</mo><mi>m</mi></mrow></math>",
"varA":"<math><mrow><mn>8</mn></mrow></math>"
}
{varB=<math><mrow><mi>m</mi></mrow></math>, ans=<math><mrow><mn>8</mn><mo>⁢</mo><mi>m</mi></mrow></math>, varA=<math><mrow><mn>8</mn></mrow></math>}

Possibility of using Generic function to convert any Java Object to JSON

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

Categories

Resources