Here is my json:
{
"timestamp":"04295d4f-2a6f-4a38-a818-52108cbdc358",
"lastFullSyncDate":null,
"ftpInfo":null,
"listingInfo":{
"itemID":"110179365615",
"itemTitle":"test",
"itemPrice":"88.2235294117647",
.......
....
.....
}
}
I have a java class named listingInfo was trying to use gson to convert the string with the key of listingInfo to the class, but i'm getting nulls for all the vars.
Gson gson = new Gson();
gson.fromJson(json, ListingInfo.class);
While trying to convert to the part class which contains the time stamp and etc i dot get the vars but the listingInfo is null inside
Is it possible to get into the nested key and only convert him to the class?
You can do it by parsing whole json tree and then extracting the nested key
String json = ...; //your json string
Gson gson = new Gson();
JsonElement element = new JsonParser().parse(json); //parse to json tree
JsonElement listingElement = element.getAsJsonObject().get("listingInfo"); // extract key
ListingInfo listingInfo = gson.fromJson(listingElement, ListingInfo.class);
Related
I have this json in java:
jsonObj = {"ps":["2.16.840.1.113883.6.1","LOINC","2.34"]}
jsonObj is response from an API, so I have it as jsonObject and I don't read it from any file.
Is there an easy way to extract all the values as individuals like jsonObj [1]?
You may Use Gson parsing library as below :
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' : 'mkyong'}";
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);
Gson gson = new Gson();
String jsonInString = "{\"userId\":\"1\",\"userName\":\"Yasir\"}";
User user= gson.fromJson(jsonInString, User.class);
or simply use:
example
JSONObject object = new JSONObject(your_json_response_string);
String IMEICheckResponse = object.getString("getIMEIResult");
for Array use :
//getting whole json string
JSONObject jsonObj = new JSONObject(jsonStr);
//extracting data array from json string
JSONArray ja_data = jsonObj.getJSONArray("data");
int length = jsonObj .length();
You should use a library to deserialize your JSON in a Java Object.
Libraries like GSON, Genson or Jackson.
Once you transform the json in a object, it will have a property called "ps" that will be an array (or a List)
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);
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 hava json in the following form:
"result":[
{"question":"3", "answer":"Doe"},
{"question":"5", "answer":"Smith"},
{"question":"8","answer":"Jones"}
]
and a Java class ->
public class UserResponses {
private Integer question;
private String answer;
//getters and setters
}
How can i parse the json into a List of UserResponses?
For example, with GSON?
JSONObject data = new JSONObject("your_json_data_here");
JSONArray questionArray = data.getJSONArray("result");
//Create an array of questions to store the data
UserResponse[] responsess = new UserResponse[questionArray.length()];
//Step through the array of JSONObjects and convert them to your Java class
Gson gson = new Gson();
for(int i = 0; i < questionArray.length(); i++){
responses[i] = gson.fromJson(
questionArray.getJSONObject(i).toString(), UserResponse.class);
}
This would be a simple way to parse the data with gson. If you wanted to do it without gson you would just have to use the getters and setters for your UserResponse class with questionArray.getJSONObject(i).getString("question") and questionArray.getJSONObject(i).getString("answer").
How can I parse the json into a List of UserResponses? For example, with GSON?
Given the "json" variable containing the json rappresenting a list of your_kind I would do as following (using reflection):
Type type = new TypeToken>() {}.getType();
List yourList = Gson().fromJSON(json, type);
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