I have liquibase.json file. Threa are:
"runningAs": {
"username": "Programer200"
}
I try to creat custom property:
liquibaseuser=root
Is it possible put value of liquibaseuser to liquibase.json ?
You could parse the json to a model and change the values.
import com.fasterxml.jackson.databind.ObjectMapper;
public class App
{
public static void main(String[] args)
{
// 1 read property
String property = "root";
// 2 read json
String json = "{\"username\": \"Programer200\"}";
// 3 map json to model
ObjectMapper mapper = new ObjectMapper();
MyModel jsonObject = mapper.readValue(json, MyModel.class);
// 4 change variables
jsonObject.username = property;
System.out.println(mapper.writer().writeValueAsString(jsonObject));
}
}
class MyModel
{
public String username;
}
You can utilize the below library for the data access.
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.4.0</version>
</dependency
After access the data you can modify the Json String. But firstly you require to get the data like below.
String user = JsonPath.read(json, "$.runningAs.username");
System.out.println(user);
In your quandary, it seem's like you require key and value, then you can utilize the map.
I am not able to unmarshall a JSON key which can hold either a string value or an another JSON Object using Jackson Library.
Ex:- Below are the two possible values.
1)
"ProviderData": {
"INVALID": "HEX",
"#text": "Sample"
}
2)
"ProviderData": "1C"
Could someone please verify and suggest me on this issue.
You can write custom deserialiser and handle these both cases or write two constructors for ProviderData POJO class and properly use JsonCreator and JsonCreator annotations. See below example:
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
public class JsonApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.readValue(jsonFile, Response.class));
}
}
class Response {
#JsonProperty("ProviderData")
private ProviderData data;
// getters, setters, toString
}
class ProviderData {
private static final String INVALID_NAME = "INVALID";
private static final String TEXT_NAME = "#text";
#JsonProperty(INVALID_NAME)
private final String invalid;
#JsonProperty(TEXT_NAME)
private final String text;
#JsonCreator(mode = JsonCreator.Mode.DELEGATING)
public ProviderData(String invalid) {
this(invalid, null);
}
#JsonCreator
public ProviderData(#JsonProperty(INVALID_NAME) String invalid, #JsonProperty(TEXT_NAME) String text) {
this.invalid = invalid;
this.text = text;
}
// getters, toString
}
For this JSON payload:
{
"ProviderData": {
"INVALID": "HEX",
"#text": "Sample"
}
}
Above example prints:
Response{data=ProviderData{invalid='HEX', text='Sample'}}
And for String primitive JSON payload:
{
"ProviderData": "1C"
}
Above example prints:
Response{data=ProviderData{invalid='1C', text='null'}}
As you can see, JSON Object is mapped properly using 2-arg constructor and String primitive is mapped using 1-arg constructor and we assume that this value means invalid key from JSON Object example.
See also:
Custom JSON Deserialization with Jackson.
sequentially deserialize using Jackson.
Deserialize strings and objects using jackson annotations in java.
you could deserialize to JsonNode and then extract the contents individually, or deserialize to an Object and use instanceof to determine if it's a Map or another type, or use a custom deserializer to unpack the data into a custom object that handles both cases.
This is my JSON from URL
https://api.myjson.com/bins/142jr
[
{
"serviceNo":"SR0000000001",
"serDate":"17",
"serMonth":"DEC",
"serYear":"2015",
"serTime":"02.30 AM",
"serApartmentName":"Galaxy Apartments"
},
{
"serviceNo":"SR0000000002",
"serDate":"19",
"serMonth":"JUN",
"serYear":"2016",
"serTime":"03.30 AM",
"serApartmentName":"The Great Apartments"
}
]
I have one ListView I want populate details from online JSON,above i given a link and sample json anybody given sample jackson code in java
Thanks for advance,
Rajesh Rajendiran
To use jackson you need to create a model class:
[
{
"serviceNo":"SR0000000001",
"serDate":"17",
"serMonth":"DEC",
"serYear":"2015",
"serTime":"02.30 AM",
"serApartmentName":"Galaxy Apartments"
},
{
"serviceNo":"SR0000000002",
"serDate":"19",
"serMonth":"JUN",
"serYear":"2016",
"serTime":"03.30 AM",
"serApartmentName":"The Great Apartments"
}
]
For the above the json the model class would be:
public class SomeClass {
private String serviceNo;
private String serDate;
private String serMonth;
private String serYear;
private String serTime;
private String serApartmentName;
#JsonProperty("serviceNo") //to bind it to serviceNo attribute of the json string
public String getServiceNo() {
return serviceNo;
}
public void setServiceNo(String sNo) { //#JsonProperty need not be specified again
serviceNo = sNo;
}
//create getter setters like above for all the properties.
//if you want to avoid a key-value from getting parsed use #JsonIgnore annotation
}
Now whenever you have the above json as string stored in a variable say jsonString use the following code to parse it:
ObjectMapper mapper = new ObjectMapper(); // create once, reuse
ArrayList<SomeClass> results = mapper.readValue(jsonString,
new TypeReference<ArrayList<ResultValue>>() { } );
results should now contain two SomeClass objects having the above json parsed as respective objects.
PS: Its been a long time since I have used Jackson for parsing so this code might need some improvements.
If you are getting this as http response then I would suggest to use spring rest template for android.
It has support for Message Converters. That way the onus of marshaling and unmarshalling.
[Update]
Here is a blog for the same :http://www.journaldev.com/2552/spring-restful-web-service-example-with-json-jackson-and-client-program
Refer Docs for more details:
http://docs.spring.io/spring-android/docs/current/reference/html/rest-template.html
I am using "org.json" for JSON. I am able to serialize any class into a JSON string, using JSONObject. However, I'm not sure how to go the other way. How does one Deserialize a JSON string back into a class instance?
This code works to serialize it. I use JSONObject, and I provide a list of field names as a second argument to the constructor - User.JSONFieldMap().
int randomValue = rnd.nextInt(10000);
String userName = "JavaUnitTest_" + randomValue;
User newUser = new User();
newUser.UserName = userName;
newUser.DisplayName = "Java Unit Test";
newUser.EmailAddress = userName + "#SomeDomainName.com";
JSONObject jsonUser = new JSONObject(newUser, User.JSONFieldMap());
String userStringified = jsonUser.toString();
I'm not sure how, or if it is possible to be able to do something like this:
User myUser = MagicJSONDeserializer.DeserializeIt("{ some JSON string}");
Thanks for any help, I come from a .net/C#/Microsoft background, so Java is very new to me.
That library does not provide such functionality directly. You can use any of hundreds of other Java JSON libraries that do, such as Gson, Jackson, or flexjson.
The indirect way of doing it would be to retrieve each value from the JSON and perform custom deserialization on that value before assigning it to an object field.
Update for someone interested in other solution. It can be achieved using com.fasterxml.jackson.databind as follows:
import com.fasterxml.jackson.databind.ObjectMapper;
String userStr = "{ \"NAME\" : \"John\" }";
User user = new ObjectMapper().readValue(userStr, User.class);
It uses ObjectMapper to convert byte[] or in this caseString to java object. This solution needs to have class User correctly annotated for example with #JsonProperty annotations. Otherwise it won't be able to match json key-values with class attributes.
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSetter;
public class User {
#JsonProperty("NAME")
String name;
#JsonGetter("NAME")
public String getName() {
return name;
}
#JsonSetter("NAME")
public void setName(String name) {
this.name = name;
}
}
This is the JSON string I have:
{"attributes":[{"nm":"ACCOUNT","lv":[{"v":{"Id":null,"State":null},"vt":"java.util.Map","cn":1}],"vt":"java.util.Map","status":"SUCCESS","lmd":13585},{"nm":"PROFILE","lv":[{"v":{"Party":null,"Ads":null},"vt":"java.util.Map","cn":2}],"vt":"java.util.Map","status":"SUCCESS","lmd":41962}]}
I need to convert the above JSON String into Pretty Print JSON Output (using Jackson), like below:
{
"attributes": [
{
"nm": "ACCOUNT",
"lv": [
{
"v": {
"Id": null,
"State": null
},
"vt": "java.util.Map",
"cn": 1
}
],
"vt": "java.util.Map",
"status": "SUCCESS",
"lmd": 13585
},
{
"nm": "PROFILE
"lv": [
{
"v": {
"Party": null,
"Ads": null
},
"vt": "java.util.Map",
"cn": 2
}
],
"vt": "java.util.Map",
"status": "SUCCESS",
"lmd": 41962
}
]
}
Can anyone provide me an example based on my example above? How to achieve this scenario? I know there are lot of examples, but I am not able to understand those properly. Any help will be appreciated with a simple example.
Updated:
Below is the code I am using:
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.defaultPrettyPrintingWriter().writeValueAsString(jsonString));
But this doesn't works with the way I needed the output as mentioned above.
Here's is the POJO I am using for the above JSON:
public class UrlInfo implements Serializable {
private List<Attributes> attribute;
}
class Attributes {
private String nm;
private List<ValueList> lv;
private String vt;
private String status;
private String lmd;
}
class ValueList {
private String vt;
private String cn;
private List<String> v;
}
Can anyone tell me whether I got the right POJO for the JSON or not?
Updated:
String result = restTemplate.getForObject(url.toString(), String.class);
ObjectMapper mapper = new ObjectMapper();
Object json = mapper.readValue(result, Object.class);
String indented = mapper.defaultPrettyPrintingWriter().writeValueAsString(json);
System.out.println(indented);//This print statement show correct way I need
model.addAttribute("response", (indented));
Below line prints out something like this:
System.out.println(indented);
{
"attributes" : [ {
"nm" : "ACCOUNT",
"error" : "null SYS00019CancellationException in CoreImpl fetchAttributes\n java.util.concurrent.CancellationException\n\tat java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:231)\n\tat java.util.concurrent.FutureTask.",
"status" : "ERROR"
} ]
}
which is the way I needed to be shown. But when I add it to model like this:
model.addAttribute("response", (indented));
And then shows it out in a resultform jsp page like below:
<fieldset>
<legend>Response:</legend>
<strong>${response}</strong><br />
</fieldset>
I get something like this:
{ "attributes" : [ { "nm" : "ACCOUNT", "error" : "null
SYS00019CancellationException in CoreImpl fetchAttributes\n
java.util.concurrent.CancellationException\n\tat
java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:231)\n\tat
java.util.concurrent.FutureTask.", "status" : "ERROR" } ] }
which I don't need. I needed the way it got printed out above. Can anyone tell me why it happened this way?
To indent any old JSON, just bind it as Object, like:
Object json = mapper.readValue(input, Object.class);
and then write it out with indentation:
String indented = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
this avoids your having to define actual POJO to map data to.
Or you can use JsonNode (JSON Tree) as well.
The simplest and also the most compact solution (for v2.3.3):
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.writeValueAsString(obj)
The new way using Jackson 1.9+ is the following:
Object json = OBJECT_MAPPER.readValue(diffResponseJson, Object.class);
String indented = OBJECT_MAPPER.writerWithDefaultPrettyPrinter()
.writeValueAsString(json);
The output will be correctly formatted!
ObjectMapper.readTree() can do this in one line:
mapper.readTree(json).toPrettyString();
Since readTree produces a JsonNode, this should pretty much always produce equivalent pretty-formatted JSON, as it JsonNode is a direct tree representation of the underlying JSON string.
Prior to Jackson 2.10
The JsonNode.toPrettyString() method was added in Jackson 2.10. Prior to that, a second call to the ObjectMapper was needed to write the pretty formatted result:
mapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(mapper.readTree(json));
For Jackson 1.9, We can use the following code for pretty print.
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationConfig.Feature.INDENT_OUTPUT);
I think, this is the simplest technique to beautify the json data,
String indented = (new JSONObject(Response)).toString(4);
where Response is a String.
Simply pass the 4(indentSpaces) in toString() method.
Note: It works fine in the android without any library. But in java you have to use the org.json library.
You can achieve this using bellow ways:
1. Using Jackson
String formattedData=new ObjectMapper().writerWithDefaultPrettyPrinter()
.writeValueAsString(YOUR_JSON_OBJECT);
Import bellow class:
import com.fasterxml.jackson.databind.ObjectMapper;
It's gradle dependency is :
compile 'com.fasterxml.jackson.core:jackson-core:2.7.3'
compile 'com.fasterxml.jackson.core:jackson-annotations:2.7.3'
compile 'com.fasterxml.jackson.core:jackson-databind:2.7.3'
2. Using Gson from Google
String formattedData=new GsonBuilder().setPrettyPrinting()
.create().toJson(YOUR_OBJECT);
Import bellow class:
import com.google.gson.Gson;
It's gradle is:
compile 'com.google.code.gson:gson:2.8.2'
Here, you can also download correct updated version from repository.
This looks like it might be the answer to your question. It says it's using Spring, but I think that should still help you in your case. Let me inline the code here so it's more convenient:
import java.io.FileReader;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectWriter;
public class Foo
{
public static void main(String[] args) throws Exception
{
ObjectMapper mapper = new ObjectMapper();
MyClass myObject = mapper.readValue(new FileReader("input.json"), MyClass.class);
// this is Jackson 1.x API only:
ObjectWriter writer = mapper.defaultPrettyPrintingWriter();
// ***IMPORTANT!!!*** for Jackson 2.x use the line below instead of the one above:
// ObjectWriter writer = mapper.writer().withDefaultPrettyPrinter();
System.out.println(writer.writeValueAsString(myObject));
}
}
class MyClass
{
String one;
String[] two;
MyOtherClass three;
public String getOne() {return one;}
void setOne(String one) {this.one = one;}
public String[] getTwo() {return two;}
void setTwo(String[] two) {this.two = two;}
public MyOtherClass getThree() {return three;}
void setThree(MyOtherClass three) {this.three = three;}
}
class MyOtherClass
{
String four;
String[] five;
public String getFour() {return four;}
void setFour(String four) {this.four = four;}
public String[] getFive() {return five;}
void setFive(String[] five) {this.five = five;}
}
Since jackson-databind:2.10 JsonNode has the toPrettyString() method to easily format JSON:
objectMapper
.readTree("{}")
.toPrettyString()
;
From the docs:
public String toPrettyString()
Alternative to toString() that will
serialize this node using Jackson default pretty-printer.
Since:
2.10
If you format the string and return object like RestApiResponse<String>, you'll get unwanted characters like escaping etc: \n, \". Solution is to convert your JSON-string into Jackson JsonNode object and return RestApiResponse<JsonNode>:
ObjectMapper mapper = new ObjectMapper();
JsonNode tree = objectMapper.readTree(jsonString);
RestApiResponse<JsonNode> response = new RestApiResponse<>();
apiResponse.setData(tree);
return response;
Anyone using POJO, DDO, or response class for returning their JSON can use spring.jackson.serialization.indent-output=true in their property file. It auto-formats the response.