{
"first":"element",
"second":"Integral",
"isThird":false,
"fourth":{
"ONE":[
{
"100":"Cars"
},
{
"200":"Truck"
}
],
"TWO":[
{
"6":"Vintage"
},
{
"4":"Sports"
}
]
}
}
I have a json where I am using Jackson to break in Java Object form. I want to know how I can break this json into simplest form using Jackson.
This is my Jackson Dependency used
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.0</version>
</dependency>
First you have to prepare a matching class structure to your JSON. If that is done instantiate an ObjectMapper in your code and grab the Objects from them.
ObjectMapper mapper = new ObjectMapper();
YourType unmarshalledJson = mapper.readValue(jsonString,YourType.class);
Use Gson Api.
JsonParser parser=new JsonParser();
JsonObject jsonObj=(JsonObject) parser.parse("Your Json String");
String first=jsonObj.get("first"); // first and second are String in json
String second=jsonObj.get("second");
JsonObject fourth=jsonObj.getAsJsonObject("fourth"); // because fourth is Object in json
// And so on......
Related
if I have to following XML document info into a string:
<Collection>
...
<Places><D>USA</D><D>BRAZIL</D><D>COREA</D></Places>
...
</Collection>
and I want to convert it into a Json that look something like:
{
"PLACES": ["USA", "BRAZIL", "COREA"]
}
Note that the <D> tags are ignored and i get the values inside of them as the values that I want into my array... How do I do that in java? I'm doing the following using org.json and jackson API:
String xml = FileUtils.readFileToString(new File(file.getAbsolutePath()));
JSONObject json = org.json.XML.toJSONObject(xml);
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT)
Object json2 = mapper.readValue(json.toString(), Object.class);
String output = mapper.writeValueAsString(json2);
System.out.println(output);
but it converts the info like this:
{
"PLACES" : {
"D" : [ "USA", "BRAZIL", "COREA" ]
}
So I want the array to be directly after "PLACES", ignoring that "D"... any suggestion? Thanks
Use XmlMapper to convert xml into POJO. Even you don't need to read file manually.
POJO (Collection class)
#JacksonXmlRootElement(localName = "Collection")
public class Collection {
#JsonProperty("PLACES")
#JacksonXmlProperty(localName = "D")
#JacksonXmlElementWrapper(localName = "Places")
List<String> places;
public List<String> getPlaces() {
return places;
}
public void setPlaces(List<String> places) {
this.places = places;
}
}
Main Method
public static void main(String[] args) throws Exception {
ObjectMapper xmlMapper = new XmlMapper();
xmlMapper.enable(SerializationFeature.INDENT_OUTPUT);
Collection c = xmlMapper.readValue(new File("/root/config.txt"), Collection.class);
System.out.println(xmlMapper.writeValueAsString(c));
ObjectMapper jsonMapper = new ObjectMapper();
jsonMapper.enable(SerializationFeature.INDENT_OUTPUT);
System.out.println(jsonMapper.writeValueAsString(c));
}
Output
<Collection>
<Places>
<D>USA</D>
<D>BRAZIL</D>
<D>COREA</D>
</Places>
</Collection>
{
"PLACES" : [ "USA", "BRAZIL", "COREA" ]
}
Xml library
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.9.5</version>
</dependency>
SimpleXml and Gson can do it:
public class Collection {
public Places Places;
}
public class Places {
#SerializedName("PLACES")
public List<String> D;
}
final String data = ...
final SimpleXml simple = new SimpleXml();
final Collection c = simple.fromXml(data, Collection.class);
final Gson gson = new Gson();
System.out.println(gson.toJson(c.Places));
Will output:
{"PLACES":["USA","BRAZIL","COREA"]}
From maven central:
<dependency>
<groupId>com.github.codemonstur</groupId>
<artifactId>simplexml</artifactId>
<version>1.4.0</version>
</dependency>
BTW if you don't like the naming you can change anything using SimpleXml annotations. I didn't need them so I didn't use them.
[
{
"updated_at":"2012-03-02 21:06:01",
"fetched_at":"2012-03-02 21:28:37.728840",
"description":null,
"language":null,
"title":"JOHN",
"url":"http://rus.JOHN.JOHN/rss.php",
"icon_url":null,
"logo_url":null,
"id":"4f4791da203d0c2d76000035",
"modified":"2012-03-02 23:28:58.840076"
},
{
"updated_at":"2012-03-02 14:07:44",
"fetched_at":"2012-03-02 21:28:37.033108",
"description":null,
"language":null,
"title":"PETER",
"url":"http://PETER.PETER.lv/rss.php",
"icon_url":null,
"logo_url":null,
"id":"4f476f61203d0c2d89000253",
"modified":"2012-03-02 23:28:57.928001"
}
]
First create one class (Json_obj) for your json data.Then you can try this :
String json_str='[ { "updated_at":"2012-03-02 21:06:01", "fetched_at":"2012-03-02 21:28:37.728840", "description":null, "language":null, "title":"JOHN", "url":"http://rus.JOHN.JOHN/rss.php", "icon_url":null, "logo_url":null, "id":"4f4791da203d0c2d76000035", "modified":"2012-03-02 23:28:58.840076" }, { "updated_at":"2012-03-02 14:07:44", "fetched_at":"2012-03-02 21:28:37.033108", "description":null, "language":null, "title":"PETER", "url":"http://PETER.PETER.lv/rss.php", "icon_url":null, "logo_url":null, "id":"4f476f61203d0c2d89000253", "modified":"2012-03-02 23:28:57.928001" } ]';
Gson gson = new Gson();
Json_obj json_obj = gson.fromJson(json_str, Json_obj.class);
Now your json data is converted in an object.You can fetch any value from that object.
I suggest you just use jackson library instead.
You can just quickly have
ObjectMapper mapper = new ObjectMapper () // this reads json to Pojo and writes Pojo to json
YourPojoClass obj = mapper.readValue (....)
Reference: mkyong.com/java/jackson-2-convert-java-object-to-from-json
I'm getting a JSON array in string like
[ { "id":"ca.Primary_Diagnosis_Dt",
"field":"ca.Primary_Diagnosis_Dt",
"type":"date",
"input":"text",
"operator":"not_equal",
"value":"2016/06/07"
},
{ "id":"ca.Clinical_Stage",
"field":"ca.Clinical_Stage",
"type":"integer",
"input":"select",
"operator":"equal",
"value":"I"
}
]
i just want to save the value of id ,operator and value in LIST please help
Online : Working code
First create a class to store your values :
class Data{
String id;
String operator;
String value;
}
Then iterate over the json :
JSONArray jsonArr = new JSONArray("[JSON Stirng]");
List<Data> dataList = new ArrayList<>();
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
Data data = new Data();
data.id = jsonObj.getString("id");
data.operator = jsonObj.getString("operator");
data.value = jsonObj.getString("value");
dataList.add(data);
}
Now dataList has your data!
P.S. : Use getter/setters in Data class
JAR : http://www.java2s.com/Code/Jar/j/Downloadjavajsonjar.htm
Use any JSON parsor eg: GSON to create an arraylist of this particular json
Iterate the arraylist
Save it :)
You can do that with a JSon library such as org.glassfish.javax.json
In Maven use
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.0.4</version>
</dependency>
Then read the string to a JsonArray:
JsonArray ja = Json.createReader(new StringReader(input)).readArray();
Then iterate over the list, map the objects to a new objects with just the values you need:
List<JsonObject> list = ja.stream()
.map(o -> (JsonObject) o)
.map(jo -> Json.createObjectBuilder()
.add("id", jo.getJsonString("id"))
.add("operator", jo.getJsonString("operator"))
.add("value", jo.getJsonString("value")).build())
.collect(Collectors.toList());
In case you could not use JsonObject as output, you may use a value object instead - just like Himanshu Tyagi proposed - and map the values to that object.
In your case, I think, the JSON should be parsed into a List<Map<String,String>>. This can be done using Jackson. Following is a method that converts a JSON string into List<Map<String,String>>:
public static List<Map<String, String>> toList(String json) throws IOException {
List<Map<String, String>> listObj;
ObjectMapper MAPPER = new ObjectMapper();
listObj = MAPPER.readValue(json, new TypeReference<ArrayList<HashMap<String, String>>>() {
});
return listObj;
}
If you have created a POJO class for it then you can use:
public static List<PojoClass> toList(String json) throws IOException {
List<PojoClass> listObj;
ObjectMapper MAPPER = new ObjectMapper();
listObj = MAPPER.readValue(json, new TypeReference<ArrayList<PojoClass>>() {
});
return listObj;
}
Maven dependency for Jackson:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.3</version>
</dependency>
I created a simple POJO:
public class LoginPojo {
private String login_request = null;
private String email = null;
private String password = null;
// getters, setters
}
After some searching I found this: JSONObject jsonObj = new JSONObject( loginPojo );
But with this I got the error:
The constructor JSONObject(LoginPojo) is undefined
I found another solution:
JSONObject loginJson = new JSONObject();
loginJson.append(loginPojo);
But this method does not exist.
So how can I convert my POJO into a JSON?
Simply use the java Gson API:
Gson gson = new GsonBuilder().create();
String json = gson.toJson(obj);// obj is your object
And then you can create a JSONObject from this json String, like this:
JSONObject jsonObj = new JSONObject(json);
Take a look at Gson user guide and this SIMPLE GSON EXAMPLE for more information.
It is possible to get a (gson) JsonObject from POJO:
JsonElement element = gson.toJsonTree(userNested);
JsonObject object = element.getAsJsonObject();
After that you can take object.entrySet() and look up all the tree.
It is the only absolutely free way in GSON to set dynamically what fields you want to see.
Jackson provides JSON parser/JSON generator as foundational building block; and adds a powerful Databinder (JSON<->POJO) and Tree Model as optional add-on blocks. This means that you can read and write JSON either as stream of tokens (Streaming API), as Plain Old Java Objects (POJOs, databind) or as Trees (Tree Model). for more reference
You have to add jackson-core-asl-x.x.x.jar, jackson-mapper-asl-x.x.x.jar libraries to configure Jackson in your project.
Modified Code :
LoginPojo loginPojo = new LoginPojo();
ObjectMapper mapper = new ObjectMapper();
try {
mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY);
// Setting values to POJO
loginPojo.setEmail("a#a.com");
loginPojo.setLogin_request("abc");
loginPojo.setPassword("abc");
// Convert user object to json string
String jsonString = mapper.writeValueAsString(loginPojo);
// Display to console
System.out.println(jsonString);
} catch (JsonGenerationException e){
e.printStackTrace();
} catch (JsonMappingException e){
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
Output :
{"login_request":"abc","email":"a#a.com","password":"abc"}
JSONObject input = new JSONObject(pojo);
This worked with latest version.
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180130</version>
</dependency>
You can also use project lombok with Gson overriding toString function. It automatically includes builders, getters and setters in order to ease the data assignment like this:
User user = User.builder().username("test").password("test").build();
Find below the example class:
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import com.google.gson.Gson;
#Data
#Builder(toBuilder = true)
#AllArgsConstructor
#NoArgsConstructor
public class User {
/* User name. */
private String username;
/* Password. */
private String password;
#Override
public String toString() {
return new Gson().toJson(this, User.class);
}
public static User fromJSON(String json) {
return new Gson().fromJson(json, User.class);
}
}
Simply you can use the below solution:
ObjectMapper mapper = new ObjectMapper();
String str = mapper.writeValueAsString(loginPojo);
JSONObject jsonObject = new JSONObject(str);
I use jackson in my project, but I think that u need a empty constructor.
public LoginPojo(){
}
You can use
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.13</version>
</dependency>
To create a JSON object:
#Test
public void whenGenerateJson_thanGenerationCorrect() throws ParseException {
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < 2; i++) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("AGE", 10);
jsonObject.put("FULL NAME", "Doe " + i);
jsonObject.put("DATE OF BIRTH", "2016/12/12 12:12:12");
jsonArray.add(jsonObject);
}
String jsonOutput = jsonArray.toJSONString();
}
Add the annotations to your POJO class like so:
#JSONField(name = "DATE OF BIRTH")
private String dateOfBirth;
etc...
Then you can simply use:
#Test
public void whenJson_thanConvertToObjectCorrect() {
Person person = new Person(20, "John", "Doe", new Date());
String jsonObject = JSON.toJSONString(person);
Person newPerson = JSON.parseObject(jsonObject, Person.class);
assertEquals(newPerson.getAge(), 0); // if we set serialize to false
assertEquals(newPerson.getFullName(), listOfPersons.get(0).getFullName());
}
You can find a more complete tutorial on the following site:
https://www.baeldung.com/fastjson
I need to serialize some objects to a JSON and send to a WebService. How can I do it using the org.json library? Or I'll have to use another one? Here is the class I need to serialize:
public class PontosUsuario {
public int idUsuario;
public String nomeUsuario;
public String CPF;
public String email;
public String sigla;
public String senha;
public String instituicao;
public ArrayList<Ponto> listaDePontos;
public PontosUsuario()
{
//criando a lista
listaDePontos = new ArrayList<Ponto>();
}
}
I only put the variables and the constructor of the class but it also have the getters and setters. So if anyone can help please
Easy way to do it without annotations is to use Gson library
Simple as that:
Gson gson = new Gson();
String json = gson.toJson(listaDePontos);
One can use the Jackson library as well.
Add Maven Dependency:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</dependency>
Simply do this:
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString( serializableObject );
The quickest and easiest way I've found to Json-ify POJOs is to use the Gson library.
This blog post gives a quick overview of using the library.
You make the http request
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
You read the Buffer
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
Log.d("Result", sb.toString());
result = sb.toString();
Create a JSONObject and pass the result string to the constructor:
JSONObject json = new JSONObject(result);
Parse the json results to your desired variables:
String usuario= json.getString("usuario");
int idperon = json.getInt("idperson");
String nombre = json.getString("nombre");
Do not forget to import:
import org.json.JSONObject;
GSON is easy to use and has relatively small memory footprint. If you loke to have even smaller footprint, you can grab:
https://github.com/ko5tik/jsonserializer
Which is tiny wrapper around stripped down GSON libraries for just POJOs
The "reference" Java implementation by Sean Leary is here on github. Make sure to have the latest version - different libraries pull in versions buggy old versions from 2009.
Java EE 7 has a JSON API in javax.json, see the Javadoc. From what I can tell, it doesn't have a simple method to marshall any object to JSON, you need to construct a JsonObject or a JsonArray.
import javax.json.*;
JsonObject value = Json.createObjectBuilder()
.add("firstName", "John")
.add("lastName", "Smith")
.add("age", 25)
.add("address", Json.createObjectBuilder()
.add("streetAddress", "21 2nd Street")
.add("city", "New York")
.add("state", "NY")
.add("postalCode", "10021"))
.add("phoneNumber", Json.createArrayBuilder()
.add(Json.createObjectBuilder()
.add("type", "home")
.add("number", "212 555-1234"))
.add(Json.createObjectBuilder()
.add("type", "fax")
.add("number", "646 555-4567")))
.build();
JsonWriter jsonWriter = Json.createWriter(...);
jsonWriter.writeObject(value);
jsonWriter.close();
But I assume the other libraries like GSON will have adapters to create objects implementing those interfaces.
After JAVAEE8 published , now you can use the new JAVAEE API JSON-B (JSR367)
Maven dependency :
<dependency>
<groupId>javax.json.bind</groupId>
<artifactId>javax.json.bind-api</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.eclipse</groupId>
<artifactId>yasson</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.1</version>
</dependency>
Here is some code snapshot :
Jsonb jsonb = JsonbBuilder.create();
// Two important API : toJson fromJson
String result = jsonb.toJson(listaDePontos);
JSON-P is also updated to 1.1 and more easy to use. JSON-P 1.1 (JSR374)
Maven dependency :
<dependency>
<groupId>javax.json</groupId>
<artifactId>javax.json-api</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.1</version>
</dependency>
Here is the runnable code snapshot :
String data = "{\"name\":\"Json\","
+ "\"age\": 29,"
+ " \"phoneNumber\": [10000,12000],"
+ "\"address\": \"test\"}";
JsonObject original = Json.createReader(new StringReader(data)).readObject();
/**getValue*/
JsonPointer pAge = Json.createPointer("/age");
JsonValue v = pAge.getValue(original);
System.out.println("age is " + v.toString());
JsonPointer pPhone = Json.createPointer("/phoneNumber/1");
System.out.println("phoneNumber 2 is " + pPhone.getValue(original).toString());