I have a list of mongo db objects List from mongo fetch
for example the DBObject contains column name and order:
student name,1
student id,2
student address,3
I would like to transpose this data for datatables ui to json like so:
[
{ title: "student name" },
{ title: "student id" },
{ title: "student address" }
]
I looked up GSON lib but it seems like i need to add annotations to my objects - no intentions of doing so.
Suppose you have your Pojo like this:
class YourPojo {
private String title;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
You can build Gson json:
final JsonArray datasets = new JsonArray();
for (String key: dbObject.keySet()) {
JsonObject dataset = new JsonObject();
dataset.addProperty("title", key);
datasets.add(dataset);
}
And then convert it to your pojo:
Type listType = new TypeToken<ArrayList<YourPojo>>(){}.getType();
List<YourPojo> yourPojoList = new Gson().fromJson(datasets, listType);
Related
I've got an JSON string from my API, looks like this:
[
{
"id": "abc",
"data": {
"Name": "Peter",
"Date": "2017/12/01"
}
},
{
"id": "def",
"data": {
"Name": "Tina",
"Date": "2017/12/20"
}
},
{
"id": "ghi",
"data": {
"Name": "Amy",
"Date": "2017/12/16"
}
}
]
Then, I use (java):
Gson gson = new Gson();
Type resultType = new TypeToken<List<Map<String, Object>>>() {
}.getType();
List<Map<String, Object>> result = gson.fromJson(info, resultType);
if I call result.get(0).toString());
then it returned:
{id=abc, data={Name=Peter, Date=2017/12/01}}
if I call result.get(0).get("id").toString();
then it returned
abc
Now I want to get the data of "data", when I call result.get(0).get("data").toString();
then it returned
{Name=Peter, Date=2017/12/01}
Finally I want to get the "Name" info, but when I tried to convert this string to Map, it cause some problem, the code is like this:
Type type = new TypeToken<Map<String, Object>>(){}.getType();
Map<String, Object> myMap = gson.fromJson(str, type);
This doesn't work. I found that maybe the string is not a general type of JSON, it is like "Name=Peter, Date=2017/12/01", but it needs "Name": "Peter", "Date": "2017/12/01" , right? Is that the problem? How can I get the data of Name? Can anyone help me?
Updated:
I found that if "Name" = "", then I couldn't get it as string type, I cannot use "data.get("Name");". But I still need it. Anyone can fix it? Thanks.
You can directly convert the response into the POJO/Model class. Check this and this
You don't need manual parsing, if you are using Gson. See how-
List<Response> responseList = new Gson().fromJson(yourJson, new TypeToken<List<Response>>() {
}.getType());
Data data = responseList.get(0).getData();
String id = responseList.get(0).getId();
String date = data.getDate();
String name = data.getName();
Isn't this magic? No manual parsing at all.
Response.java class
public class Response {
private Data data;
private String id;
public void setData(Data data) {
this.data = data;
}
public Data getData() {
return data;
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
}
Data.java class
public class Data {
private String date;
private String name;
public void setDate(String date) {
this.date = date;
}
public String getDate() {
return date;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
How to generate Pojo classes? So here is several websites jsonschema2pojo. Also many Android Studio plugins available, I use RoboPOJOGenerator.
First of all, your JSON is malformed, it shouldn't have a comma after date.
and to answer your question, don't use map at all.
If you really want to do it without creating a model and additional classes, do it this way:
Gson gson = new Gson();
Type resultType = new TypeToken<List<JsonObject>>() {}.getType();
List<JsonObject> result = gson.fromJson(info, resultType);
System.out.println(result.get(0).get("data").toString());
JsonObject data = result.get(0).get("data").getAsJsonObject();
System.out.println(data.get("Name"));
I have a list of object from type Person:
String id
String name
String address
String workPlace
I want to create a new list contain Person objects but only with 2 fields: id and name.
I want to create a json from that list later that looks like this:
[
{
"id": "767384",
"name": "Bob",
},
{
"id": "202330",
"name": "Alice",
}
]
How can I do it? Thanks!
The library is com.google.gson.JsonArray and org.json.JSONObject
First thing to do is create a JSON Array.
JsonArray jsonPersonList = new JsonArray();
Then create a loop (assuming there is a list known as personList ).
for(Person person : personList)
Then create a new json object inside the loop.
JsonObject personJson = new JsonObject();
put the person attributes inside the json object.
personJson.addProperty("id" , person.getId()); //Assuming getters,setters
personJson.addProperty("name" , person.getName());
In the end of the loop, add the personJson to JsonPersonList.
jsonPersonList.add(personJson);
After the loop you would have a json list with your desired persons.
Example method:
public JsonArray getPersonJsonList(ArrayList<Person> personList){
JsonArray jsonPersonList = new JsonArray();
for(Person person : personList){
JsonObject personJson = new JsonObject();
personJson.addProperty("id" , person.getId());
personJson.addProperty("name" , person.getName());
jsonPersonList.add(personJson);
}
return jsonPersonList;
}
You could also create a new result Object or DTO, like that
public class ResultPerson {
String id;
String name;
public ResultPerson(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
and then you can map your Person list to your new list by using java stream and convert it to json by making use of ObjectMapper
ObjectMapper objectMapper = new ObjectMapper();
List<ResultPerson> results = persons.stream().map(person -> new ResultPerson(person.getId(), person.getName()))
.collect(Collectors.toList());
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
try {
String json = ow.writeValueAsString(results);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
You'd need to add jackson-databind as dependency:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.4</version>
</dependency>
if you don't use maven you can download the jar and add it to your classpath
I have a test.json file with data:
{
"name":"tet",
"id":"1",
"age" : "34"
}
Now when I query select * from test; should show me the result as
name id age
-----------
tet 1 34
Is it possible to directly query a JSON Object as we do for XML?
The popular Jackson XML library supports JsonPointer since version 2.3. This is a query language similar to XPath
Input
[{
"name":"tet",
"id":"1",
"age" : "34"
},{
"name":"tet",
"id":"1",
"age" : "34"
},{
"name":"tet",
"id":"1",
"age" : "34"
},{
"name":"tet",
"id":"1",
"age" : "34"
}]
Example
ObjectMapper objectMapper = new ObjectMapper();
JsonNode root = objectMapper.readTree(new File("foo.json"));
System.out.println(root.at("/0/name").asText());
I would say you can either try looking for a library which allows you to search throught JSON data or to convert your json to JSONObjects and query your data in a Object Oriented way.
Perhaps this thread will help:
Query a JSONObject in java
there is no way to query directly from the Json, if you want you have to create a new class that will do your requirement, OR you can use the ObjectMapper (download and add to your class path) from jackson-all-1.9.0.jar, and create a new transfer Object TestTO.java expose the setters and getters you will get your data like below..
1.create TestTO.java
public class TestTO{
private String name;
private int id;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
2.read your data from the object.
final ObjectMapper mapper = new ObjectMapper();
Test test = mapper.readValue(yourJson.json, TestTO.class);
String name = test.getName();
int id = test.getId();
int age = test.getAge();
if your json contains the multiple test objects, use an test array like below, it will give you the array of tests, you can iterate over and get the data, like below.
final ObjectMapper mapper = new ObjectMapper();
TestTO[] test = mapper.readValue(yourJson.json, TestTO.class[]);
for(Test tst:test){
String name = test.getName();
int id = test.getId();
int age = test.getAge();
}
I have the following json data (patients.json):
{
"A" : {
"name" : "Tom",
"age" : 12
},
"B" : {
"name" : "Jim",
"age" : 54
}
}
Using the Jackson JSON library, how can I get something like the following:
HashMap<String, ???> patients = objectMapper.readValue(new File("patients.json"), ???);
String Aname = patients.get("A").get("name");
int Aname = patients.get("A").get("age");
Deserialize your JSON into Jackson's JSON Object type, ObjectNode. You can then traverse it as you see fit.
For example
ObjectNode patients = objectMapper.readValue(new File("test.json"), ObjectNode.class);
// you can check if it is actually an ObjectNode with JsonNode#isObject()
ObjectNode nodeA = (ObjectNode)patients.get("A");
String name = nodeA.get("name").asText();
int age = (int) nodeA.get("age").asLong();
Note that the methods asXyz() return default values if the target node cannot be converted to that type. You can check with the corresponding isXyz() methods before invoking them.
You could create a class to map your patients to;
private static class Patient {
#JsonProperty("name")
private String name;
#JsonProperty("age")
private int age;
public Patient() { }
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
Then read your json into it via jackson
HashMap<String, Patient> patients = objectMapper.readValue(new File("patients.json"), new TypeReference<HashMap<String,Patient>>() {});
Patient patientA = patients.get("A");
String patientAName = patientA.getName();
int pateintAAge = patientA.getAge();
I am trying to load my Json into my class
public User() {
this.fbId = 0;
this.email = "";
this.name = "";
this.thumb = "";
this.gender = "";
this.location = "";
this.relationship = null;
this.friends = new ArrayList();
}
{
users:{
user:{
name:'the name',
email:'some#email.com',
friends:{
user:{
name:'another name',
email:'this#email.com',
friends:{
user:{
name:'yet another name',
email:'another#email.com'
}
}
}
}
}
}
}
I am struggling to get GSON to load the user details into the above Java object with the following code
User user = gson.fromJson(this.json, User.class);
The JSON is invalid. A collection is not to be represented by {}. It stands for an object. A collection/array is to be represented by [] with commaseparated objects.
Here's how the JSON should look like:
{
users:[{
name: "name1",
email: "email1",
friends:[{
name: "name2",
email: "email2",
friends:[{
name: "name3",
email: "email3"
},
{
name: "name4",
email: "email4"
}]
}]
}]
}
(note that I added one more friend to the deepest nested friend, so that you understand how to specify multiple objects in a collection)
Given this JSON, your wrapper class should look like this:
public class Data {
private List<User> users;
// +getters/setters
}
public class User {
private String name;
private String email;
private List<User> friends;
// +getters/setters
}
and then to convert it, use
Data data = gson.fromJson(this.json, Data.class);
and to get the users, use
List<User> users = data.getUsers();