I want to decode a json string like {"username":["emmet"]} to a Map<String,String[]> object.
using following code:
String json = "{\"username\":[\"emmet\"]}";
Gson gson = new GsonBuilder().create();
Map<String,String[]> map = new HashMap<>();
map = (Map<String,String[]>)gson.fromJson(json, map.getClass());
String[] val = map.get("username");
System.out.println(val);
this exception occurs:
Exception in thread "main" java.lang.ClassCastException: java.util.ArrayList cannot be cast to [Ljava.lang.String;
at com.company.Main.main(Main.java:16)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Gson has decoded my object as a Map<String, ArrayList<String>> object instead of Map<String,String[]> object. How can I force gson to decode my object as Array not ArrayList?
I'm using gson-2.8.1.
Gson converts json array to a java List, so when you trying to get the usernames as String[] you getting an ClassCastException
If you want to get it as a String[] use it that way :
String json = "{\"username\":[\"emmet\"]}";
Gson gson = new GsonBuilder().create();
Map<String,List<String>> map = new HashMap<>();
map = (Map<String,List<String>>)gson.fromJson(json, map.getClass());
List<String> usernames = map.get("username");
String[] val = usernames.toArray(new String[0]);
System.out.println(val);
That will work for you
You can parse everything out and place it into a Map manually. Here is some code that demonstrates how you could do this
String jsonString = "{\"username\":[\"emmet\"]}";
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = jsonParser.parse(jsonString).getAsJsonObject();
Set<String> keys = jsonObject.keySet();
Map<String, String[]> map = new HashMap<>();
for(String key:keys){
JsonElement jsonElement = jsonObject.get(key);
if(jsonElement.isJsonArray()){
JsonArray jsonArray = jsonElement.getAsJsonArray();
String[] strings = new String[jsonArray.size()];
for(int i = 0; i < jsonArray.size(); i++){
strings[i] = jsonArray.get(i).getAsString();
}
map.put(key, strings);
} else {
//Handle other instances such as JsonObject, JsonNull, and JsonPrimitive
}
}
Related
I have String "[{...}]" and I want convert it to JSONArray, and then to List list = new List I was trying this solution, and this is my code
public void RestoreData()
{
String toConvert = "[{...}]" // I don't place full String, but it's typical JSONArray, but in String
ArrayList<myClass> listdata = new ArrayList<myClass>();
JsonObject jsonObject = new JsonObject();
JSONArray jArray = (JSONArray)jsonObject;
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
listdata.add(jArray.getString(i));
}
}
}
And when I'm trying to compile this I get 2 errors:
In JSONArray jArray = (JSONArray)jsonObject; I get error 'Incovertible types; cannot cast 'org.json.JSONObject' to 'org.json.JSONArray'.
And second: in listdata.add(jArray.getString(i)); I get error 'unhandled exception org.json.JSONException'.
I'm new in Java and I work with Json for the first time.
EDIT
A small truncated example of the Json string:
[{"lootArmorGain":0,"lootBlockGain":0,"lootCost":93500,"lootCritGain":2,"lootCritPowerGain":0,"lootDamageAbsorptionGain":0,"lootDamageGain":0,
}]
I think what you want is:
public void RestoreData()
{
try{
String toConvert = "[{...}]" // I don't place full String, but it's typical JSONArray, but in String
ArrayList<MyClass> listdata = new ArrayList<MyClass>();
JSONArray jsonArray = new JSONArray(toConvert);
if (jsonArray != null) {
Gson gson = new Gson();
for (int i=0;i<jsonArray.length();i++){
String json = jsonArray.getJSONObject(i).toString();
MyClass obj = gson.fromJson(json, MyClass.class);
listdata.add(obj);
}
}
}catch(JSONException e){
e.printStackTrace();
}
}
To convert from JSONOject to your custom class use GSON, see above.
compile 'com.google.code.gson:gson:2.8.4'
Note that your custom class need to have an empty constructor as well as getters and setters in order to make gson work.
I think best approach will be using Google Gson Library.
String toConvert = "[{...}]"
Type listType = new TypeToken<List<myClass>>() {}.getType();
List<myClass> yourList = new Gson().fromJson(toConvert, listType);
You dont need to get each position manually.
For simplicity you can also use Jackson api
ObjectMapper objectMapper = new ObjectMapper();
TypeFactory typeFactory = objectMapper.getTypeFactory();
List<SomeClass> someClassList = objectMapper.readValue(jsonString,typeFactory.constructCollectionType(List.class, SomeClass.class));
I have pass two values from ajax to my servlet.
I used
JsonObject data = new Gson().fromJson(request.getReader(), JsonObject.class);
System.out.println(data);
and this is the output
{"0":"31/01/2017","1":"19/01/2017"}
Now I want to convert this data into a java arraylist but not really sure how.
I tried
Gson googleJson = new Gson();
JsonObject data = googleJson.fromJson(request.getReader(), JsonObject.class);
System.out.println(data);
JsonArray jsonArr = data.getAsJsonArray();
// jsonArr.
ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
for(int i=0; i< jsonObjList.size(); i++) {
System.out.println(jsonObjList.get(i));
}
But got an error
java.lang.IllegalStateException: This is not a JSON Array.
Someone help me please? thanks.
Create instance of JsonArray then add json element to that array using key.
Here is your solution :
Gson googleJson = new Gson();
JsonObject data = googleJson.fromJson(request.getReader(), JsonObject.class);
System.out.println(data);
JsonArray jsonArr = new JsonArray();
for(Entry<String, JsonElement> entry : data.entrySet()) {
jsonArr.add(data.get(entry.getKey()));
}
ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
for(int i = 0; i < jsonObjList.size(); i++) {
System.out.println(jsonObjList.get(i));
}
For a Json to be a valid JsonArray object you should have it to a proper format. Can you change your json string return from your ajax? If yes you should change it to something like this:
Gson googleJson = new Gson();
JsonObject data = googleJson.fromJson("{test: [{\"0\":\"31/01/2017\"},{\"1\":\"19/01/2017\"}]}", JsonObject.class);
System.out.println(data);
JsonArray jsonArr = data.getAsJsonArray("test");
ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
for(int i=0; i< jsonObjList.size(); i++) {
System.out.println(jsonObjList.get(i));
}
If not you should parse it by your self and convert it to everything you want.
In java I am trying to convert a Map to json string. using code below
private void sendResponse(Map<String, String> responseMap) throws IOException
{
PrintStream ps = new PrintStream(clientSocket.getOutputStream());
JSONObject json = new JSONObject(responseMap);
ps.println(json.toString());
}
The variable
json results in {"empty":false} the map contains valid keyvalue pairs.
The map contains values like this
responseMap.put("response", "ok");
responseMap.put("versionname", "dummy");
responseMap.put("versioncode", "dummy");
responseMap.put("package","dummy");
responseMap.put("deviceid", "unknown");
responseMap.put("devicename", "dummy");
responseMap.put("synclocation", null);
responseMap.put("extra", "");
The code I am using comes from https://github.com/douglascrockford/JSON-java
any ideas why its not working
?
Map to Json, Json to Map? I use Gson lib. There is no problem.
Map to Json String
Gson gson = new GsonBuilder().setPrettyPrinting().create();
Map<String, String> map = new HashMap<String, String>();
map.put("111", "AAAAA");
map.put("222", "BBBBB");
String mapString = gson.toJson(map);
System.out.println(mapString);
Output
{
"222": "BBBBB",
"111": "AAAAA"
}
Json String to Map
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String mapString = "{\"222\": \"BBBBB\",\"111\": \"AAAAA\"}";
Map<String, String> map = gson.fromJson(mapString, Map.class);
System.out.println(map.get("111"));
Output
AAAAA
I want to convert my ArrayList<object> to a JSON String and back to ArrayList<object>
But I really don't know how to do that :
Something like :
Convert
ArrayList<data> arrayData = new ArrayList<data>();
JSONObject retObject = new JSONObject();
retObject.put("data", new JSONArray(arrayData ));
Return convert
idk...
You can consider using a JSON library like Google's Gson library to store and retrieve objects as JSON strings. This is a lightweight library, well regarded and popular. It would be an ideal solution in your case with minimal work required. e.g.,
// How to store JSON string
Gson gson = new Gson();
// This can be any object. Does not have to be an arraylist.
String json = gson.toJson(myAppsArr);
// How to retrieve your Java object back from the string
Gson gson = new Gson();
DataObject obj = gson.fromJson(arrayString, ArrayList.class);
Using Jackson:
ObjectMapper mapper = new ObjectMapper();
String listAsJson = mapper.writeValueAsString(oldList);
List<Object> newList= mapper.readValue(listAsJson ,new TypeReference<List<Object>>() {});
ArrayList<Product> arrayData = new ArrayList<Product>();
Gson gson = new Gson();
convert list to json object
String jsonCartList = gson.toJson(cartList);
convert json to your list
List<Product> prodList = gson.fromJson(jsonCartList, Product.class);
I'm Workin with Mongo using Jongo, when I do a query I receive a LinkedHashMap as result.
Iterator one = (Iterator) friends.find(query).projection("{_id:0}").as(Object.class);
while (one.hasNext()) {
LinkedHashMap data = new LinkedHashMap();
data = (LinkedHashMap) one.next();
String content = data.toString();
}
the problem is that if the json is {"user":"something"} content will be {user=something}, it is not a json is only toString method from HashMap.
How I can get the original JSON?
I don't have a class to map the response and it isn't a solution create a map class, that is why I use a Object.class.
If you have access to some JSON library, it seems like that's the way to go.
If using org.json library, use public JSONObject(java.util.Map map):
String jsonString = new JSONObject(data).toString()
If Gson, use the gson.toJson() method mentioned by #hellboy:
String jsonString = new Gson().toJson(data, Map.class);
You can use Gson library from Google to convert any object to JSON. Here is an example to convert LinkedHashMap to json -
Gson gson = new Gson();
String json = gson.toJson(map,LinkedHashMap.class);
One of the com.mongodb.BasicDBObject constructors takes a Map as input. Then you just have to call the toString() on the BasicDBObject object.
Iterator one = (Iterator) friends.find(query).projection("{_id:0}").as(Object.class);
while (one.hasNext()) {
LinkedHashMap data= new LinkedHashMap();
data= (LinkedHashMap) one.next();
com.mongodb.BasicDBObject bdo = new com.mongodb.BasicDBObject(data);
String json = bdo.toString();
}
I resolved the problem using the following code:
Iterator one = (Iterator) friends.find(query).projection("{_id:0}").as(Object.class);
while (one.hasNext()) {
Map data= new HashMap();
data= (HashMap) one.next();
JSONObject d = new JSONObject();
d.putAll(data);
String content=d.toString();
}
if(data instanceof LinkedHashMap){
json=new Gson.toJson(data,Map.class).toString();
}
else{
json=data.toString();
}
return Document.parse(json);