Custom pretty printer using Jackson library - java

I have data in a Map object and I want to print it in a json format. I tried using DefaultPrettyPrinter
mapper.writerWithDefaultPrettyPrinter().writeValue(filePath, mapObject);
but the format is not what I expected. I am getting output like this:
{
"arrVals" : ["value-1","value-2"]
}
I want output like this:
{
"arrVals" : [
"value-1",
"value-2"
]
}

You need indentation before Array Values. You can use indentArraysWith method to set the Lf2SpacesIdenter object which will basically add a line feed followed by 2 spaces.
This might solve your problem.
DefaultPrettyPrinter pp = new DefaultPrettyPrinter();
pp.indentArraysWith(new Lf2SpacesIndenter());
mapper.writer(pp).writeValue(filePath, mapObject);

Related

How to get the value of particular attribute from a JSON using RestAssured.JsonPath

I'm trying to hit an API thru RestAssured + Java code and able to get some response as you can see in this post. But I need to get the value of particular node / attribute i.e. errorParams which is present in the JSON and print in the Java Console.
{
"customerId":null,
"errorDetails":[
[
{
"errorCode":"ABC_2021",
"errorParams":"Input Customer Id"
}
]
]
}
I tried like this and not working.
JsonPath jsp = new JsonPath(response.getBody().asString());
System.out.println(jsp.getString("errorDetails.errorParams"));
System.out.println(jsp.getString("$['errorDetails']['errorParams']"));
Any suggestions or working script would be helpful for me.
Thanks,
Karunagara Pandi G
That one works just fine:
System.out.println(jsp.getString("errorDetails.errorParams"));
So I assumed you retrieving your JsonPath in the wrong way, try:
JsonPath jsp = response.jsonPath();
or
JsonPath jsp = new JsonPath(response.asString());
you can use the following snippet it works for me
System.out.println(response.jsonPath().getString("errorDetails.errorParams"));

Creating objects with JSON in Java

Using an API, I am calling for an options chain with lots of different data. It looks like this:
```
[
putCall=PUT
symbol=AAPL_012023P100
description=AAPL Jan 20 2023 100 Put
exchangeName=OPR
bidPrice=10.05
askPrice=10.3
lastPrice=10.15
bidAskSize=78X102
markPrice=10.18
bidSize=78
askSize=102
lastSize=0
highPrice=10.15
lowPrice=9.85
openPrice=0.0
closePrice=9.98
totalVolume=334
quoteTimeInLong=1612904400035
tradeTimeInLong=1612903831902
netChange=0.17
volatility=37.645
delta=-0.195
gamma=0.004
theta=-0.014
vega=0.524
rho=-0.676
timeValue=10.15
openInterest=7941
isInTheMoney=false
theoreticalOptionValue=10.175
theoreticalVolatility=29.0
isMini=false
isNonStandard=false
optionDeliverablesList=<null>
strikePrice=100.0
expirationDate=1674248400000
expirationType=R
multiplier=100.0
settlementType=
deliverableNote=
isIndexOption=<null>
percentChange=1.75
markChange=0.2
markPercentChange=2.01
otherFields={lastTradingDay=1674262800000, daysToExpiration=709, tradeDate=null}
]], ```
This is one part of the many it returns. I need all of them. So, using Jackson I understand how to convert this to JSON using something like this:
```
ObjectMapper mapper = new ObjectMapper();
String data = eq.toString();
mapper.writerWithDefaultPrettyPrinter().writeValueAsString(data);
Now, this cleans it up some, but now for what I actually need.. I need 3 things out of all this. I would like to create an object for each one of these things with the following fields: openInterest, totalVolume, and description.
I have tried searching for this, but I can't figure it out for when you have multiple values. What I posted above is just one of many entries that the API returns me. I would really appreciate some help :)
this:
[
putCall=PUT
symbol=AAPL_012023P100
/*bla di bla whatever*/
markPercentChange=2.01
otherFields={lastTradingDay=1674262800000, daysToExpiration=709, tradeDate=null}
]], ``
I'ma call this leSRC
JSONObject zTHING = new JSONObject();
zTHING.put("openInterest", leSRC.getJSONObject("openInterest"));
zTHING.put("totalVolume", leSRC.getJSONObject("totalVolume"));
zTHING.put("description", leSRC.getJSONObject("description"));
Your zTHING object should have those 3 KvP's set up correctly.

how to create the data model for this { "words":[3,4,5] } json in kotlin

I was trying to write a data model to send a JSON to the API and delete some fields
the JSON should contain the id of some words and it should look exactly like this :
{
"words":[3,4,5]
}
as I know and also as the https://jsonformatter.org/ said the data class should be something like the following piece of code:
data class words(var id: List<Int>)
but the problem is when I pass the data to it and toast it to see if it's a valid JSON request for the server the output will be this :
words(id=[1,2,4,5])
and it's not what it should be.
as I said I need this :
{
"words":[3,4,5]
}
I think the following should work.
data class AnyNameYouWant(val words: List<Int>)
I think the name of the data class really doesn't matter as it would finally represent the { } object syntax of json.
Looking in the comments, I think it's better to use some logging library like Timber. If you are using Retrofit then use can also use HttpLoggingInterceptor and set the level to Body that will print the body of the response in the logcat.

Java : Parsing a Json formated String to Java

I do a Action on Middle ware and if its success i get the Value as
String result = ["RESULT","DELETE","OK"]
And in Case if the Operation is Failed i get the resposne as
String result = ["RESULT","DELETE","ERROR"]
I need to know if the Operation is success Or Fail so for this i have done this
public class Test {
public static void main(String args[]) {
String result = "[\"RESULT\",\"DELETE\",\"ERROR\"]";
if (!result.contains("ERROR")) {
System.out.println("success");
} else {
System.out.println("Failed");
}
}
This is working fine , but not sure if this has any negative impact / or in cases the code may Fail .
Please suggest if there is a better approach .
Your code can fail if, for instance, you get a success message containing ERROR (not likely, but can happen).
You should use a library to parse the result into a List/Array, look here on StackOverflow for a ton of solutions for parsing Json Strings to Objects in Java (Jackson is a library to do this, for instance).
You should also validate against a pre-set number of hypothesis, for instance, creating an enum for the possible result types, and checking if it's one of them.
I would suggest to use object presentation instead of array here:
{
"RESULT": {
"operation": "DELETE",
"status" : "ERROR"
}
}
There is you can find a lot of tools to parse JSON in Java objects:
http://www.json.org/
In other case it will be hard to extend set of codes. E.g.
String result = "[\"RESULT\",\"CREATE\",\"USER\", \"LOGIN\", \"ERROR\", \"SUCCESS\"]";
Was there error? or user with login ERROR was successfully created?
String[] result = {"RESULT","DELETE","OK"};
if(Arrays.asList(result).contains("OK"))
System.out.println("Ok");
Try Arrays.asList() method to check given arrays contains that element or not.

json parsing problems

data: [
{
type: "earnings"
info: {
earnings: 45.6
dividends: 4052.94
gains: 0
expenses: 3935.24
shares_bought: 0
shares_bought_user_count: 0
shares_sold: 0
shares_sold_user_count: 0
}
created: "2011-07-04 11:46:17"
}
{
type: "mentions"
info: [
{
type_id: "twitter"
mentioner_ticker: "LOANS"
mentioner_full_name: "ERICK STROBEL"
}
]
created: "2011-06-10 23:03:02"
}
]
Here's my problem : like you can see the "info" is different in each of one, one is a json object, and one is a json array, i usually choose Gson to take the data, but with Gson we can't do this kind of thing . How can i make it work ?
If you want to use Gson, then to handle the issue where the same JSON element value is sometimes an array and sometimes an object, custom deserialization processing is necessary. I posted an example of this in the Parsing JSON with GSON, object sometimes contains list sometimes contains object post.
If the "info" element object has different elements based on type, and so you want polymorphic deserialization behavior to deserialize to the correct type of object, with Gson you'll also need to implement custom deserialization processing. How to do that has been covered in other StackOverflow.com posts. I posted a link to four different such questions and answers (some with code examples) in the Can I instantiate a superclass and have a particular subclass be instantiated based on the parameters supplied thread. In this thread, the particular structure of the JSON objects to deserialize varies from the examples I just linked, because the element to indicate the type is external of the object to be deserialized, but if you can understand the other examples, then handling the problem here should be easy.
Both key and value have to be within quotes, and you need to separate definitions with commas:
{
"key0": "value0",
"key1": "value1",
"key2": [ "value2_0", "value2_1" ]
}
That should do the trick!
The info object should be of the same type with every type.
So check the type first. Pseudocode:
if (data.get('type').equals("mentions") {
json_arr = data.get('info');
}
else if (data.get('type').equals("earnings") {
json_obj = data.get('info');
}
I'm not sure that helps, cause I'm not sure I understand the question.
Use simply org.json classes that are available in android: http://developer.android.com/reference/org/json/package-summary.html
You will get a dynamic structure that you will be able to traverse, without the limitations of strong typing.....
This is not a "usual" way of doing things in Java (where strong typing is default) but IMHO in many situations even in Java it is ok to do some dynamic processing. Flexibility is better but price to pay is lack of compile-time type verification... Which in many cases is ok.
If changing libraries is an option you could have a look at Jackson, its Simple Data Binding mode should allow you to deserialize an object like you describe about. A part of the doc that is probably quite important is this, your example would already need JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES to work...
Clarification for Bruce: true, in Jackson's Full Data Binding mode, but not in Simple Data Binding mode. This is simple data binding:
public static void main(String[] args) throws IOException {
File src = new File("test.json");
ObjectMapper mapper = new ObjectMapper();
mapper.configure(JsonParser.Feature. ALLOW_UNQUOTED_FIELD_NAMES, true);
mapper.configure(JsonParser.Feature.ALLOW_COMMENTS,true);
Object root = mapper.readValue(src, Object.class);
Map<?,?> rootAsMap = mapper.readValue(src, Map.class);
System.out.println(rootAsMap);
}
which with OP's sightly corrected sample JSON data gives:
{data=[{type=earnings, info={earnings=45.6, dividends=4052.94, gains=0,
expenses=3935.24, shares_bought=0, shares_bought_user_count=0, shares_sold=0,
shares_sold_user_count=0}, created=2011-07-04 11:46:17}, {type=mentions,
info=[{type_id=twitter, mentioner_ticker=LOANS, mentioner_full_name=ERICK STROBEL}],
created=2011-06-10 23:03:02}]}
OK, some hand-coding needed to wire up this Map to the original data, but quite often less is more and such mapping code, being dead simple has the advantage of being very easy to read/maintain later on.

Categories