I need to include some JSON data inside an XML output (I know it might not be the best way, but the system requires it). This problem is part of a Spring REST project. The Java method which generates the XML is annotated as
#RequestMapping(value = "/TEST/pid",
method = RequestMethod.GET, produces = "application/xml")
public String xmlGenerator(String pid){
// definition
}
I could incorporate the JSON data inside the XML output, but the JSON data is not pretty printed. The JSON data is pretty printed before it gets inserted into the XML, but within the XML the JSON is prints out everything in a line. The XML output with JSON data is as follows. Any suggestion how I could pretty print the JSON; the XML is already pretty printed. Appreciate any help. Thanks!
<asec ID="1234-AM0">
<wrap MIMETYPE="application/json" LABEL="JSON DATA">
<xmlData>
<asTest>
{ "pid" : "112233", "pData" : { "type" : "image", "derivatives" : [ { "url" : "//test/url/test1.jpg", "width" : "1538", "height" : "600", "size" : "45168" }, { "url" : "//test/url/test2.jpg", "width" : "64", "height" : "64", "size" : "890" }, { "url" : "//test/url/test3.jpg", "width" : "2888", "height" : "1127", "size" : "180680" } ] } }
</asTest>
</xmlData>
</wrap>
</asec>
--EDIT--
Not sure why someone would mark the question as duplicate. My question is not how to pretty print JSON in Java, I could do that already. My question is how to pretty print the JSON content inside an XML output.
Related
I would like to generate a signature from my Java code, this is my method:
public static String hmacWithJava(String algorithm, String data, String key)
throws NoSuchAlgorithmException, InvalidKeyException {
Mac mac = Mac.getInstance(algorithm);
mac.init(new SecretKeySpec(key.getBytes(), algorithm));
String hexFormatSignature = "sha256=" + HexFormat.of().formatHex(mac.doFinal(data.getBytes()));
return hexFormatSignature;
}
where
algorithm="HmacSHA256"`
key="testKey";
data="{
"action" : "created",
"installation" : {
"id" : 2,
"account" : {
"login" : "testUser",
"type" : "User"
}
},
"sender" : {
"login" : "testUser",
"type" : "User"
}
}"
hexFormatSignature="sha256=11e20c46886a8e681fd2a3ad0e3a100d42579e1cf95417dd27acc80cedadabd5"
If I put the same payload in the https://www.devglan.com/online-tools/hmac-sha256-online tool y got the next result: "11e20c46886a8e681fd2a3ad0e3a100d42579e1cf95417dd27acc80cedadabd5"
But this is not the correct signature, the correct one must be:"aef0567d41bb28abe34d9202cd019668a8b35f65dd1981d22a74de5c19823b6a"
The difference I have noticed is related with the json format, I mean the one generated from Jackson has less espaces o more enters that the one I am using manually and is generating the correct signature.
Left side is the one generated form Java code and right side the one that someone give me and its working.
This is the comparison between both text and they have the same values, but different indentation format, in fact if I add a space in the original payload I will have a different signature. Is there a way to solve this issue? Maybe I need to configure something to get the correct format from Java?
This is the manual payload, which is working:
{
"action": "created",
"installation" : {
"id": 2,
"account":{
"login": "testUser",
"type": "User"
}
},
"sender" : {
"login" : "testUser",
"type" : "User"
}
}
I am using Jackson to get the Json String from the Payload:
String jsonStr = obj.writerWithDefaultPrettyPrinter().writeValueAsString(payload);
And my Payload object looks like this:
Payload{action='created', installation=model.Installation#3d121db3, sender=model.User#3b07a0d6}
The issue in question is as follows:-
I have a POJO with a list of Apple objects , say applesList.
This is stored in Cosmos DB.
When applesList is null, the get endpoint works fine. I get the Pojo as is.
When applesList is populated with apples, i get the error as given in the Title.
How do i fix this?
Json that works with get :-
{
"userId" : "123",
"applesList" : null
}
Json that gives stated error on get, applesList is populated by api :-
{
"userId" : "123",
"applesList" : [
{
"color" : "red",
"weight" : "150 g"
},
{
"color" : "green",
"weight" : "200 g"
}
]
}
Edit :- missed mentioning Cosmos DB SQL API
Change applesList to an array.
Alright, i've got a simple question. I have a simple Document in MongoDB which holds a sub-document called "penalties".
Now i want to find the Document (here with the _id "Cammeritz") by a String in the sub-document ("penalties"), e.g. "penaltyid = 0f77d885-6597-3f47-afb1-0cee2ea3ece1". Can you maybe help me? Best would be an explanation for Java but it is okay if you maybe just help with a normal MongoDB query.
{
"_id" : "Cammeritz",
"penalties" : [
{
"_id" : null,
"date" : ISODate("2017-09-25T20:01:23.582Z"),
"penaltyid" : "0f77d885-6597-3f47-afb1-0cee2ea3ece1",
"reason" : "Hacking",
"teammember" : "Luis",
"type" : "ban"
},
{
"_id" : null,
"date" : ISODate("2017-09-25T20:01:23.594Z"),
"penaltyid" : "7f5411b0-e66a-33b3-ac4f-4f3159aa88a9",
"reason" : "Spam",
"teammember" : "BluingFX",
"type" : "kick"
}
],
"isBanned" : true,
"isMuted" : false
}
Oops, I misread your question. You'll need to use dot notation. db.collection.find( { penalties.penaltyid: '0f77d885-6597-3f47-afb1-0cee2ea3ece1' } ) For more info see Query on a Nested Field.
Original answer:
db.collection.find( { penalties: "0f77d885-6597-3f47-afb1-0cee2ea3ece1" } ) should work. For more see Query an Array for an Element from the mongodb docs. I'm not very familiar with Java so I can't help much there.
I am using Elastic Search Server. I need to get records based on starting character of a field value in source JSON.
JSON:
Index JSON1 : "{\"id\":\"1\",\"message\":\"welcome to elastic search\"}"
Index JSON2 : "{\"id\":\"1\",\"message\":\"Hellow world\"}"
Code:
String selectedCharacter = "w";
PrefixQueryBuilder queryBuilder = QueryBuilders.prefixQuery("message", selectedCharacter);
builder.setQuery(queryBuilder);
By using the above code, I am getting both the records. I need only 'Index JSON1'. Please give any solution to achieve this. Thanks in advance.
By default, Elasticsearch will "tokenize" string fields.
It means that your message fields are considered as a multiple terms fields. For JSON1 : ["welcome", "to", "elastic", "search"] and JSON2 : ["Hellow", "world"].
When you make your query, ElasticSearch will try to match on of the term, that's why you get JSON1 for the "welcome" term et JSON2 for the "world" term.
If you want your message field to be "untokenized" (treated as a single string), you have to explicitly set the mapping of this field to keyword. This is done by using the Mapping API.
You can look at :
the keyword analyzer doc : http://www.elasticsearch.org/guide/reference/index-modules/analysis/keyword-analyzer/
the mapping API doc : http://www.elasticsearch.org/guide/reference/api/admin-indices-put-mapping/
If you need a keyword analyzer but case-insensitive, you need to define a custom analyzer with a lowercase filter (you will probably need to delete and recreate your index for that). Ex :
$ curl -XPUT 'localhost:9200/test/_settings' -d '
{
"index": {
"analysis" : {
"analyzer" : {
"lowercaseAnalyzer": {
"type": "custom",
"tokenizer": "keyword",
"filter": ["lowercase"]
}
}
}
}
}
And then you define your mapping with this custom analyzer instead of keyword :
"message" : {"type" : "string", "analyzer" : "lowercaseAnalyzer"}
You can also test your analyzer using the analyze API. Ex :
$ curl -XGET 'localhost:9200/test/_analyze?analyzer=lowercaseAnalyzer&pretty=true' -d 'Hello world'
{
"tokens" : [ {
"token" : "hello world",
"start_offset" : 0,
"end_offset" : 11,
"type" : "word",
"position" : 1
} ]
}
You can see all the available tokenizers and filters in the analysis documentation : http://www.elasticsearch.org/guide/reference/index-modules/analysis/
I pass out a ajax get which contains a parameter i.e. date added to db.
Java queries the DB for results of persons added on this date, and builds a JSON object for me like so:
{
"resultdata" : { "rowsReturned" : "2", "fetchTime" : "180"}
"row_1" : { "name" : "Larry", "sex" : "m", "age" : "26", "location" : "seattle" }
"row_2" : { "name" : "Pedro", "sex" : "m", "age" : "22", "location" : "unknown" }
}
I can then return the JSON object as a String. I'd then like to dynamically build a table based on these results.
First of all is the JSON object correct for building a table?
The result data tells me how many rows and the time taken in milliseconds, followed by however many rows in that particular format.
I then want to create a table inside a specific div element once these results are returned to my browser on the fly with no page refreshes etc.
so Id expect Table headers with titles of each column - followed by you guessed it 2 rows.
How is the best way to go about doing this. I am familiar with jQuery, JSON is totally new to me and dealing with JSON in jQuery is something i'm keen on learning.
Any help is much appreciated.
you can use jsonlint to validate your json.
Yours is not valid. It's missing some ',':
{
"resultdata" : {
"rowsReturned" : "2",
"fetchTime" : "180"
}, // <--
"row_1" : {
"name" : "Larry",
"sex" : "m",
"age" : "26",
"location" : "seattle"
}, // <--
"row_2" : {
"name" : "Pedro",
"sex" : "m",
"age" : "22",
"location" : "unknown"
}
}
I've made a little DEMO of one possible way how to loop through the json with for-in-loops
for (key in json) {
loops through the json and stores each key in the 'key' variable.
in your case 'resultdata','row_1','row_2'.
So to access the data for each key you write json[key] which translates to json['row_1'] for example.
Now you do the same thing for the row_1 object with:
for(key1 in json[key])
key1 are now the keys in the row_1 object: 'name','sex',...
to access the data now you'll write json[key][key1] which would be json['row_1']['name'] for example.
of course it's advisable to give the keys meaningful names to avoid confusion like in my example:)
Your JSON looks fine for building a table.
You'll want to use $.getJSON() to fetch the JSON data, as it will automatically parse the JSON into an object for you. If you need the advanced features of $.ajax(), you can call $.parseJSON() on the returned data from the AJAX call and it will parse the JSON into an object.