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.
Related
I am getting a response from a firebase function and dialogflow which hold some information that I need for further implementations.
The response is a JSON, which I hold in mResultFromDialogFlow, which is a HashMap (String, Object) type variable.
I've searched other threads like this, but the strange thing was that my problem is at column 2, not 1 and I don't see the problem in the json.
Here is the gson part. The error is thrown on the line with Properties!
Gson _gson = new Gson();
String _json = _gson.toJson(mResultFromDialogFlow.get("parameters"));
Properties data = _gson.fromJson(_json, Properties.class);
mTime = data.getProperty("date"); // String type variable
mDateFromUser = data.getProperty("time"); // String type variable
This is the response JSON:
{"date":"2019-07-19T12:00:00+03:00","time":"2019-07-19T14:00:00+03:00"}
That looks like a JSON string converted to JSON. I suspect mResultFromDialogFlow.get("parameters") already returns a JSON string. With toJson(), you convert a JSON string to JSON.
If you try
Properties data = _gson.fromJson(mResultFromDialogFlow.get("parameters"), Properties.class);
it'll probably work.
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);
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.
Are there any libraries to convert JSON in String/jackson/org.JSON.JSONOBJECT/etc... to a JSON schema?
So far, the only generator I found covert Java classes to JSON schemas. I'm about to write my own converted, but it'd be nice if I didn't have to re-invent the wheel.
looks like there isn't. I had to write my own generator.
Yes there is: https://github.com/java-json-tools/json-schema-validator. It ingests Jacson's JsonNode containing the schema definition and can validate JSON data against that schema.
You can use GSON library.
Convert Java object to JSON:
Gson gson = new Gson();
Staff obj = new Staff();
// 1. Java object to JSON, and save into a file
gson.toJson(obj, new FileWriter("D:\\file.json"));
// 2. Java object to JSON, and assign to a String
String jsonInString = gson.toJson(obj);
Convert JSON to Java object:
Gson gson = new Gson();
// 1. JSON to Java object, read it from a file.
Staff staff = gson.fromJson(new FileReader("D:\\file.json"), Staff.class);
// 2. JSON to Java object, read it from a Json String.
String jsonInString = "{'name' : 'foo'}";
Staff staff = gson.fromJson(jsonInString, Staff.class);
// JSON to JsonElement, convert to String later.
JsonElement json = gson.fromJson(new FileReader("D:\\file.json"), JsonElement.class);
String result = gson.toJson(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