I have a JSON string of the format:
resp = '{"result": [{x: 1, y:2}, {x:3, y:4}]}'
I want to convert the data from "result" key into list of objects. Something like:
List<MyCustomObj> data = new Gson()
.fromJson(resp, new TypeToken<ArrayList<MyCustomObj>>(){}.getType());
Is there a way to specify in above statement to fetch from the key "result"?
Just create a DTO that describes the structure of JSON, like:
#Getter #Setter
public class Response {
#Getter #Setter
public static class MyCustomObject {
private int x;
private int y;
}
private List<MyCustomObject> result;
}
Then it is just:
Response resp = gson.fromJson(json, Response.class);
List<MyCustomObject> result = resp.getResult();
It might be a good idea to keep the JSON format and the data structure in sync instead of some special parsing. There might not be any performance boost gained.
Related
I am using JackSon to parse the following JSON:
{
"AwardID": "1111111",
"AwardTitle": "Test Title",
"Effort":
"[
{
"PersonFirstName": "Jon",
"PersonLastName": "Snow"
}
]"
}
I would like to flatten this to be used in the following class:
public class Award {
private String awardId;
private String awardTitle;
private String personFirstName;
private String personLastName;
}
I have tried the following and have gotten the first two values, but I haven't been able to get the values from Effort trying to use JsonUnwrapped. I noted that it doesn't work with arrays, but I am trying the objectMapper.configure(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS, true) configuration in the main method used to get the values.
public class Award {
#JsonProperty("AwardID")
private String awardId;
#JsonProperty("AwardTitle")
private String awardTitle;
#JsonUnwrapped
private Effort effort;
}
public class Effort {
private String personFirstName;
private String personLastName;
}
Note that I only expect one value in the Effort array from the API response at this time.
What is recommended to try next? Thank you!
The easiest way is having a List<Effort> if you have a JSON Array.
If there is always 1 item for Effort, the returning JSON should not have Effort as a JSON Array and instead should be a JSON Object.
But if you can only handle it codewise, you can have something like this (Note that there should always contain one item in Effort, otherwise it will throw Exception):
public class Award {
#JsonProperty("AwardID")
private String awardId;
#JsonProperty("AwardTitle")
private String awardTitle;
#JsonProperty("Effort")
private Effort effort;
}
public class Effort {
#JsonProperty("PersonFirstName")
private String personFirstName;
#JsonProperty("PersonLastName")
private String personLastName;
}
And your ObjectMapper needs to be enabled with DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS as well:
ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS);
Award award = mapper.readValue(rawJson, Award.class); // rawJson is your JSON String
And it should have the following output:
Award(awardId=1111111, awardTitle=Test Title, effort=Effort(personFirstName=Jon, personLastName=Snow))
Note that the annotation #JsonUnwrapped can only apply on JSON Object, not JSON Array:
Value is serialized as JSON Object (can not unwrap JSON arrays using this mechanism)
I have a simple Java object that has a String property that contains serialized java objects:
#Data
private class Test {
int id;
String data;
}
The data is created with
test.setData(mapper.writeValueAsString(anyJavaObjectThatShouldBeSerialized));
Then I send the Test Object to another server, where I want to deserialize the object from the data property into a JSONNode:
JsonNode node = mapper.readTree(test.getData());
The problem is, that the result of readTree is a TextNode and not a JsonNode. Therefore I can not access the properties of the serialized data.
The problem might be that the serialized object is interpreted as a String because when I print it it has quotationsmarks around it:
"{\"id\":39,\"name\":\"Im a test value\"}"
How do I get a JsonNode from the String that contains serialized objects? Please note that the data can be ANY Java object, that's why I serialized it into a String.
Make a double deserialization - first deserialize the string payload to json, then deserialize the json to class, or JsonNode in your case.
public class Temp {
public static void main(String[] args) throws Exception {
String payload = //your string payload;
ObjectMapper mapper = new ObjectMapper();
String json = mapper.readValue(payload, String.class);
JsonNode node = mapper.readTree(json);
}
}
As you noted, the cause is that you are making double serialization - first when setting the data field, then again when sending data to the other server.
You can avoid this double serialization/deserialization by making data an object.
#Data
class Test {
int id;
Object data;
}
test.setData(anyJavaObjectThatShouldBeSerialized);
Like this it will be serialized like JsonObject.
{
"id": 39,
"name": "Im a test value"
}
I am using GSON to decrypt some JSON that I get from a PHP site, with the layout of:
[{"bellname":"Hey!","date":"2013-09-11"},{"bellname":"Haaaaey!","date":"2013-09-01"}]
I want to put this into a HashMap, and have seen that I need to create a class to do this. That is the part that I do not understand. This is what I have so far:
public class MySQLDB {
private BellName bellName;
private BellDate bellDate;
public static class BellName {
private String bn;
}
public static class BellDate {
private String date;
}
}
Where would I go from here? If you need to see my PHP code, here it is:
<?php
mysql_connect("localhost", "*******", "******");
mysql_select_db("tests");
$q1 = mysql_query("SELECT `bellname`, `date` FROM `bells`");
if($q1) {
$que1 = array();
while($a1 = mysql_fetch_assoc($q1)) {
$que1[] = $a1;
}
$json1 = json_encode($que1);
echo $json1;
}
?>
All this PHP code does is put a "mysql_fetch_assoc" reply into JSON.
Please help, if you could tell me how to fix this?
Thanks.
public class MySQLEntry {
public String bellname;
public String date;
}
// ...
Gson gson = new Gson();
MySQLEntry[] entryArray = gson.fromJson(yourJsonString, MySQLEntry[].class);
Answer by jpossi is the most appropriate. But just for you to know json object could be represented as Map in Java. And json array could be represented as List. So in your case you also can do this:
Gson gson = new Gson();
Type type = new TypeToken<List<Map<String,String>>>(){}.getType();
List<Map<String, String>> value = gson.fromJson("[{\"bellname\":\"Hey!\",\"date\":\"2013-09-11\"},{\"bellname\":\"Haaaaey!\",\"date\":\"2013-09-01\"}]", type);
System.out.println(value);
But deserializing in object is better then deserializing in collection of Strings in most cases.
I have a model class method which returns a list of objects which contains all the registered user details. I want to fetch the list resturned by all() method and convert the data into JSON object and pass it to the view like a string. How can I do this conversion of this array list to JSON object?
I was unable to do this by below:
ObjectMapper mapper = new ObjectMapper();
JSONObject json = new JSONObject();
JsonNodeFactory jsonnode = JsonNodeFactory.instance;
ObjectNode result = new ObjectNode(jsonnode);
for (int i = 0; i < list.size(); i++) {
json.put(list.get(i).fname, list.get(i));
System.out.println(json.get("fname"));
}
#Entity
class Mydata extends Model {
#Id
public Long Id;
public String fname;
public String lname;
public String city;
public String state;
/****************** READ/select OPERATION *****************/
public static Finder < Long, Mydata > finder = new Finder(Long.class, Mydata.class);
public static List < Mydata > all() {
return finder.all();
}
public static void createuser(Mydata user) {
user.save();
}
}
To convert ArrayList to Json, just download Open Source json utility from:
http://json.org/java/ or Jar file from here
And just do:
JSONArray jsonAraay = new JSONArray(your_array_list);
That's it
Note: You should have setter/getter in your POJO/MODEL class to convert arraylist to json
Don't bother with org.json, use Jackson all the way:
// list is a List<MyData>
final ObjectMapper mapper = new ObjectMapper();
final Map<String, MyData> map = new HashMap<>();
for (final MyData data: list)
map.put(data.fname, data);
final JsonNode json = mapper.valueToTree(map);
You could use all sorts of third party libraries like others here have suggested, or just use Play's own simplified methods for this (found in play.libs.Json) which works with Jackson objects, but it is integrated into the framework and requires a lot less code to use, for example:
JsonNode myJsonNode = Json.toJson(MyListObject); which converts the List to a JsonNode object, then use something like String jsonResult = Json.stringify(myJsonNode); to convert it into a string representation.
If you are using the JSON in a template, don't forget to wrap it in something like #Html(myJsonString) so it will not escape anything. Otherwise, if you are just outputting the pure JSON to the browser, a simple return ok(jsonResult); will work as Play will automatically set the content type.
Reference link: http://www.playframework.com/documentation/api/2.0/java/play/libs/Json.html
have you looked at this:
http://www.json.org/javadoc/org/json/JSONObject.html#valueToString(java.lang.Object)
JSONObject.valueToString(<<your list of custom object>> OR <<objects>> OR <<map>>)
works just fine...there are some other methods on that lib, if you are interested....
I'm trying to use GSON 2.2.2 (for the very first time) to map JSON into a Java POJO. I'm hitting a 3rd party RESTful web service and this is an example of the JSON I'm getting back:
{
"response": {
"job":{
"eta":-1,
"status":"approved",
"mt":1,
"lc_tgt":"fr",
"body_src":"Please translated me.",
"body_tgt":"S'il vous plaît traduire moi.",
"unit_count":3,
"tier":"machine",
"credits":0,
"ctime":"2013-02-07 14:56:12.391963",
"lc_src":"en",
"slug":"0",
"job_id":"NULL"
}
},
"opstat":"ok"
}
The POJO I'm trying to map this into is:
public class Job {
// correlates to "eta"
private int eta;
// correlates to "body_src"
private String sourceBody;
// correlates to "ctime"
private java.util.Date creationTimestamp;
// Getters and setters for all 3 properties
}
When I run the following code, I don't get any exceptions, but the print statement just prints "null":
// Hit the 3rd party service and get the JSON (example above).
JSONObject json = hitRestfulWebService();
Gson gson = new Gson();
// json.toString = "{response":{"job":{ ..."
Job job = gson.fromJson(json.toString(), Job.class);
System.out.println(job.getSourceBody());
My only guess is that GSON can't figure out how to map the 3 JSON fields to my 3 Job properties. Can someone help me figure out what this mapping needs to be? Thanks in advance.
You can use annotations to define, which json field gets mapped to which object member, e.g.:
class SomeClass
{
#SerializedName("body-src")
String myString1;
#SerializedName("header-src")
String myString2;
...
public class Response{
private Job job;
//generate setter and getter
}
public class Job {
// correlates to "eta"
private int eta;
// correlates to "body_src"
private String sourceBody;
// correlates to "ctime"
private java.util.Date creationTimestamp;
// Getters and setters for all 3 properties
}
now in Gson
JSONObject json = hitRestfulWebService();
Gson gson = new Gson();
// json.toString = "{response":{"job":{ ..."
Job job = gson.fromJson(json.toString(), Response.class);
use not response but response.job
not
{ "response": {..
use
{ "eva": ..
this may help;
String a = "{\"response\": {\"job\":{\"eta\":-1,\"status\":\"approved\",\"mt\":1,\"lc_tgt\":\"fr\",\"body_src\":\"Please translated me.\",\"body_tgt\":\"S'il vous plaît traduire moi.\",\"unit_count\":3,\"tier\":\"machine\",\"credits\":0,\"ctime\":\"2013-02-07 14:56:12.391963\",\"lc_src\":\"en\",\"slug\":\"0\",\"job_id\":\"NULL\"}},\"opstat\":\"ok\"}";
Job j = I.gson().fromJson(
((JsonObject) ((JsonObject) new JsonParser().parse(a)).get("response")).get("job"), Job.class);
System.out.println(j.getEta());