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}]
Related
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.
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>}
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'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.
I have problem when trying to parse with minimum value to map in Android.
There some sample JSON format with more information ex:
[{id:"1", name:"sql"},{id:"2",name:"android"},{id:"3",name:"mvc"}]
This that example most common to use and easy to use just use getString("id") or getValue("name").
But how do I parse to map using this JSON format with just only string and value minimum format to java map collection using looping. And because the string json will always different one with another. ex:
{"1":"sql", "2":"android", "3":"mvc"}
Thank
You need to get a list of all the keys, loop over them and add them to your map as shown in the example below:
String s = "{menu:{\"1\":\"sql\", \"2\":\"android\", \"3\":\"mvc\"}}";
JSONObject jObject = new JSONObject(s);
JSONObject menu = jObject.getJSONObject("menu");
Map<String,String> map = new HashMap<String,String>();
Iterator iter = menu.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = menu.getString(key);
map.put(key,value);
}
My pseudocode example will be as follows:
JSONArray jsonArray = "[{id:\"1\", name:\"sql\"},{id:\"2\",name:\"android\"},{id:\"3\",name:\"mvc\"}]";
JSON newJson = new JSON();
for (each json in jsonArray) {
String id = json.get("id");
String name = json.get("name");
newJson.put(id, name);
}
return newJson;