Control characters in Json causing JsonParsingException - java

I have this java method:
public class ReadIssues {
// Reads from a Json object
protected JsonArray readJson() throws IOException {
JsonArray issueArray = null;
ClassLoader cl = Thread.currentThread().getContextClassLoader();
// Get input stream for reading the specified resource
InputStream inputStream = cl.getResourceAsStream("GitHubIssue.json");
// Create JsonReader to read JSON data from a stream
Reader reader = new InputStreamReader(inputStream, "UTF-8");
JsonReader jsonReader = Json.createReader(reader);
try{
// Create an object model in memory
issueArray = jsonReader.readArray();
System.out.println("ReadIssues issueArray: " + issueArray);
}
finally {
if (inputStream != null) {
inputStream.close();
}
if (jsonReader != null) {
jsonReader.close();
}
}
return issueArray;
}
It throws this exception:
Exception in thread "main" javax.json.stream.JsonParsingException: Unexpected char 117 at (line no=1, column no=5, offset=4)
at org.glassfish.json.JsonTokenizer.unexpectedChar(JsonTokenizer.java:601)
at org.glassfish.json.JsonTokenizer.nextToken(JsonTokenizer.java:418)
at org.glassfish.json.JsonParserImpl$ObjectContext.getNextEvent(JsonParserImpl.java:453)
at org.glassfish.json.JsonParserImpl.next(JsonParserImpl.java:363)
at org.glassfish.json.JsonParserImpl.getObject(JsonParserImpl.java:333)
at org.glassfish.json.JsonParserImpl.getValue(JsonParserImpl.java:182)
at org.glassfish.json.JsonParserImpl.getArray(JsonParserImpl.java:326)
at org.glassfish.json.JsonParserImpl.getArray(JsonParserImpl.java:164)
at org.glassfish.json.JsonReaderImpl.readArray(JsonReaderImpl.java:129)
at paulcarron.issuetracker.ReadIssues.readJson(ReadIssues.java:42)
at paulcarron.issuetracker.App.main(App.java:22)
The problem seems to be issueArray = jsonReader.readArray();. I think that body value in my JSON contains characters such as \n and \r.
I came across one post that suggested doing something like json = json.replaceAll("\r?\n", ""); but that was where json was a String. What should I do in my case where I'm using a JsonReader object?
JSON Sample
[ { url: 'https://api.github.com/repos/TestOrg/test2/issues/4',
repository_url: 'https://api.github.com/repos/TestOrg/test2',
labels_url: 'https://api.github.com/repos/TestOrg/test2/issues/4/labels{/name}',
comments_url: 'https://api.github.com/repos/TestOrg/test2/issues/4/comments',
events_url: 'https://api.github.com/repos/TestOrg/test2/issues/4/events',
html_url: 'https://github.com/TestOrg/test2/issues/4',
id: 347593311,
node_id: 'MDU6SXNzdWUzNDc1OTMzMTE=',
number: 4,
title: 'test issue 2',
user:
{ login: 'my-repo',
id: 32067576,
node_id: 'MDQ6VXNlcjMyMDY3NTc2',
avatar_url: 'https://avatars1.githubusercontent.com/u/32067576?v=4',
gravatar_id: '',
url: 'https://api.github.com/users/my-repo',
html_url: 'https://github.com/my-repo',
followers_url: 'https://api.github.com/users/my-repo/followers',
following_url: 'https://api.github.com/users/my-repo/following{/other_user}',
gists_url: 'https://api.github.com/users/my-repo/gists{/gist_id}',
starred_url: 'https://api.github.com/users/my-repo/starred{/owner}{/repo}',
subscriptions_url: 'https://api.github.com/users/my-repo/subscriptions',
organizations_url: 'https://api.github.com/users/my-repo/orgs',
repos_url: 'https://api.github.com/users/my-repo/repos',
events_url: 'https://api.github.com/users/my-repo/events{/privacy}',
received_events_url: 'https://api.github.com/users/my-repo/received_events',
type: 'User',
site_admin: false },
labels: [],
state: 'open',
locked: false,
assignee: null,
assignees: [],
milestone: null,
comments: 0,
created_at: '2018-08-04T06:34:50Z',
updated_at: '2018-08-04T06:34:50Z',
closed_at: null,
author_association: 'CONTRIBUTOR',
body: 'In order to help resolve your issue as quickly as possible please provice the following information when \r\n\r\n1. What is the issue?\r\nAnother one!\r\n\r\n2. What are the steps to recreate the issue?\r\n\r\n\r\n3. Do you have any relevant code samples? If so, please provice them.\r\n\r\n\r\n4. Have you made any specific configurations?\r\n\r\n\r\n5. Do you get an error? If so please include it and any stack trace.\r\n\r\n\r\n6. What version of the API are you using?\r\n',
performed_via_github_app: null,
score: 1 },
{ url: 'https://api.github.com/repos/TestOrg/test2/issues/2',
repository_url: 'https://api.github.com/repos/TestOrg/test2',
labels_url: 'https://api.github.com/repos/TestOrg/test2/issues/2/labels{/name}',
comments_url: 'https://api.github.com/repos/TestOrg/test2/issues/2/comments',
events_url: 'https://api.github.com/repos/TestOrg/test2/issues/2/events',
html_url: 'https://github.com/TestOrg/test2/issues/2',
id: 324450775,
node_id: 'MDU6SXNzdWUzMjQ0NTA3NzU=',
number: 2,
title: 'Something really bad',
user:
{ login: 'my-repo',
id: 32067576,
node_id: 'MDQ6VXNlcjMyMDY3NTc2',
avatar_url: 'https://avatars1.githubusercontent.com/u/32067576?v=4',
gravatar_id: '',
url: 'https://api.github.com/users/my-repo',
html_url: 'https://github.com/my-repo',
followers_url: 'https://api.github.com/users/my-repo/followers',
following_url: 'https://api.github.com/users/my-repo/following{/other_user}',
gists_url: 'https://api.github.com/users/my-repo/gists{/gist_id}',
starred_url: 'https://api.github.com/users/my-repo/starred{/owner}{/repo}',
subscriptions_url: 'https://api.github.com/users/my-repo/subscriptions',
organizations_url: 'https://api.github.com/users/my-repo/orgs',
repos_url: 'https://api.github.com/users/my-repo/repos',
events_url: 'https://api.github.com/users/my-repo/events{/privacy}',
received_events_url: 'https://api.github.com/users/my-repo/received_events',
type: 'User',
site_admin: false },
labels: [],
state: 'open',
locked: false,
assignee: null,
assignees: [],
milestone: null,
comments: 1,
created_at: '2018-05-18T15:15:21Z',
updated_at: '2018-06-22T12:45:17Z',
closed_at: null,
author_association: 'CONTRIBUTOR',
body: 'In order to help resolve your issue as quickly as possible please provice the following information when \r\n\r\n1. What is the issue?\r\nIts all going wrong!!\r\n\r\n2. What are the steps to recreate the issue?\r\nStep 1\r\nStep 2\r\nStep n\r\n\r\n\r\n3. Do you have any relevant code samples? If so, please provice them.\r\nbla\r\n\r\n4. Have you made any specific configurations?\r\nN/A\r\n\r\n5. Do you get an error? If so please include it and any stack trace.\r\nError: Invalid input\r\n\r\n6. What version of the API are you using?\r\n1.2.0\r\n',
performed_via_github_app: null,
score: 1 } ]

Your input is not valid JSON. The first line is the best example.
[ { url: 'https://api.github.com/repos/TestOrg/test2/issues/4',
All object key names in JSON need to be in quotes. Hence, first line corrected:
[ { "url": 'https://api.github.com/repos/TestOrg/test2/issues/4',
Ditto for all the other key names in your objects. Your input is actually valid JavaScript. So to correct your string, I just pasted your original text into a javascript console (node or the browser F12 console will work) and did this:
x = <paste of your string above>
JSON.stringify(x)
Then I ran the output (sans leading and trailing quotes) through https://jsonformatter.org/ to pretty print to give you back the corrected text below.
As a matter of fact, just using the online pretty printer was how I found the parse error to begin with.
[
{
"url": "https://api.github.com/repos/TestOrg/test2/issues/4",
"repository_url": "https://api.github.com/repos/TestOrg/test2",
"labels_url": "https://api.github.com/repos/TestOrg/test2/issues/4/labels{/name}",
"comments_url": "https://api.github.com/repos/TestOrg/test2/issues/4/comments",
"events_url": "https://api.github.com/repos/TestOrg/test2/issues/4/events",
"html_url": "https://github.com/TestOrg/test2/issues/4",
"id": 347593311,
"node_id": "MDU6SXNzdWUzNDc1OTMzMTE=",
"number": 4,
"title": "test issue 2",
"user": {
"login": "my-repo",
"id": 32067576,
"node_id": "MDQ6VXNlcjMyMDY3NTc2",
"avatar_url": "https://avatars1.githubusercontent.com/u/32067576?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/my-repo",
"html_url": "https://github.com/my-repo",
"followers_url": "https://api.github.com/users/my-repo/followers",
"following_url": "https://api.github.com/users/my-repo/following{/other_user}",
"gists_url": "https://api.github.com/users/my-repo/gists{/gist_id}",
"starred_url": "https://api.github.com/users/my-repo/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/my-repo/subscriptions",
"organizations_url": "https://api.github.com/users/my-repo/orgs",
"repos_url": "https://api.github.com/users/my-repo/repos",
"events_url": "https://api.github.com/users/my-repo/events{/privacy}",
"received_events_url": "https://api.github.com/users/my-repo/received_events",
"type": "User",
"site_admin": false
},
"labels": [],
"state": "open",
"locked": false,
"assignee": null,
"assignees": [],
"milestone": null,
"comments": 0,
"created_at": "2018-08-04T06:34:50Z",
"updated_at": "2018-08-04T06:34:50Z",
"closed_at": null,
"author_association": "CONTRIBUTOR",
"body": "In order to help resolve your issue as quickly as possible please provice the following information when \r\n\r\n1. What is the issue?\r\nAnother one!\r\n\r\n2. What are the steps to recreate the issue?\r\n\r\n\r\n3. Do you have any relevant code samples? If so, please provice them.\r\n\r\n\r\n4. Have you made any specific configurations?\r\n\r\n\r\n5. Do you get an error? If so please include it and any stack trace.\r\n\r\n\r\n6. What version of the API are you using?\r\n",
"performed_via_github_app": null,
"score": 1
},
{
"url": "https://api.github.com/repos/TestOrg/test2/issues/2",
"repository_url": "https://api.github.com/repos/TestOrg/test2",
"labels_url": "https://api.github.com/repos/TestOrg/test2/issues/2/labels{/name}",
"comments_url": "https://api.github.com/repos/TestOrg/test2/issues/2/comments",
"events_url": "https://api.github.com/repos/TestOrg/test2/issues/2/events",
"html_url": "https://github.com/TestOrg/test2/issues/2",
"id": 324450775,
"node_id": "MDU6SXNzdWUzMjQ0NTA3NzU=",
"number": 2,
"title": "Something really bad",
"user": {
"login": "my-repo",
"id": 32067576,
"node_id": "MDQ6VXNlcjMyMDY3NTc2",
"avatar_url": "https://avatars1.githubusercontent.com/u/32067576?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/my-repo",
"html_url": "https://github.com/my-repo",
"followers_url": "https://api.github.com/users/my-repo/followers",
"following_url": "https://api.github.com/users/my-repo/following{/other_user}",
"gists_url": "https://api.github.com/users/my-repo/gists{/gist_id}",
"starred_url": "https://api.github.com/users/my-repo/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/my-repo/subscriptions",
"organizations_url": "https://api.github.com/users/my-repo/orgs",
"repos_url": "https://api.github.com/users/my-repo/repos",
"events_url": "https://api.github.com/users/my-repo/events{/privacy}",
"received_events_url": "https://api.github.com/users/my-repo/received_events",
"type": "User",
"site_admin": false
},
"labels": [],
"state": "open",
"locked": false,
"assignee": null,
"assignees": [],
"milestone": null,
"comments": 1,
"created_at": "2018-05-18T15:15:21Z",
"updated_at": "2018-06-22T12:45:17Z",
"closed_at": null,
"author_association": "CONTRIBUTOR",
"body": "In order to help resolve your issue as quickly as possible please provice the following information when \r\n\r\n1. What is the issue?\r\nIts all going wrong!!\r\n\r\n2. What are the steps to recreate the issue?\r\nStep 1\r\nStep 2\r\nStep n\r\n\r\n\r\n3. Do you have any relevant code samples? If so, please provice them.\r\nbla\r\n\r\n4. Have you made any specific configurations?\r\nN/A\r\n\r\n5. Do you get an error? If so please include it and any stack trace.\r\nError: Invalid input\r\n\r\n6. What version of the API are you using?\r\n1.2.0\r\n",
"performed_via_github_app": null,
"score": 1
}
]

Related

Django JsonResponse parsing error in Android

This is the JSON response I am getting from the server :
{
"0": {
"pk": 41,
"fields": {
"heading": "Empty Lecture Slot",
"notification": "There is a free lecture available right now for TE B on 2018-05-02 8:00-9:00",
"date": "2018-04-25",
"priority": 1,
"has_read": false,
"action": "/dashboard/set_substitute/91959"
},
"model": "Dashboard.specificnotification"
}
}
Here is the Java code used for parsing this JSON object :
JSONObject jsonObject = new JSONObject(response);
This is the error I am getting in the catch block :
org.json.JSONException: No value for {"0": {"pk": 41, "fields": {"heading": "Empty Lecture Slot", "notification": "There is a free lecture available right now for TE B on 2018-05-02 8:00-9:00", "date": "2018-04-25", "priority": 1, "has_read": false, "action": "/dashboard/set_substitute/91959"}, "model": "Dashboard.specificnotification"}}
How do I parse this object in Android.
Im not sure, but doesn't JSON arrays start like this?:
[
{
}
]
Also the "0" seems to be not required. It will be automatically ordered
EDIT: you can also check online if your json is valid. Just google Json formatter.

Mule 3.7.3 - Dataveawe Message Transformer Encoding Wrongly

I am using mule to transform some webservice responses on my project, and currently i am using DataWeave message transformer.
JSON that i should transform :
{
"odata.metadata": "http://mchwtatmsdb/Across/CrossTank/api/v1/$metadata#Translations",
"value": [
{
"SourceSentence": {
"Id": 2750901,
"Text": "Refrigerator:",
"Language": 1033
},
"TargetSentence": {
"Id": 2750902,
"Text": "Kühlschrank:",
"Language": 1031
},
"Id": 2264817,
"Similarity": 100,
"CreationDate": "2009-02-25T12:56:15",
"Creator": "41e8d49d-0de7-4a96-a220-af96d94fe4b0",
"ModificationDate": "2009-02-25T12:56:15",
"Modificator": "00000000-0000-0000-0000-000000000000",
"State": "SmartInserted",
"Note": ""
},
{
"SourceSentence": {
"Id": 2750906,
"Text": "Refrigerator*",
"Language": 1033
},
"TargetSentence": {
"Id": 2750907,
"Text": "Kühlschrank*",
"Language": 1031
},
"Id": 2264822,
"Similarity": 100,
"CreationDate": "2009-02-25T12:55:46",
"Creator": "41e8d49d-0de7-4a96-a220-af96d94fe4b0",
"ModificationDate": "2009-02-25T12:55:46",
"Modificator": "00000000-0000-0000-0000-000000000000",
"State": "SmartInserted",
"Note": ""
}
]
}
I am basically using transformer, define metadatas respective to json files that is included in the project.
So transformer part is so simple :
<dw:set-payload><![CDATA[%dw 1.0
%output application/json
---
{
"odata.metadata": payload."odata.metadata",
value: payload.value map ((value , indexOfValue) -> {
SourceSentence: {
Id: value.SourceSentence.Id,
Text: value.SourceSentence.Text as :string,
Language: value.SourceSentence.Language
},
TargetSentence: {
Id: value.TargetSentence.Id,
Text: value.TargetSentence.Text,
Language: value.TargetSentence.Language
},
Similarity: value.Similarity
})
}]]></dw:set-payload>
Transformation runs in expected way and it gets the necessary fields that i've set in dataweave transformer, after transformer implemented on json string, it changes the encoding somehow, and output doesn't show special characters. Such as:
{
"odata.metadata": "http://mchwtatmsdb/Across/CrossTank/api/v1/$metadata#Translations",
"value": [
{
"SourceSentence": {
"Id": 2750901,
"Text": "Refrigerator:",
"Language": 1033
},
"TargetSentence": {
"Id": 2750902,
"Text": "K252hlschrank:",
"Language": 1031
},
"Similarity": 100
},
{
"SourceSentence": {
"Id": 2750906,
"Text": "Refrigerator*",
"Language": 1033
},
"TargetSentence": {
"Id": 2750907,
"Text": "K252hlschrank*",
"Language": 1031
},
"Similarity": 100
}
]
}
"Text": "K252hlschrank*" part of the string is showing "ü" character as "252" i tried to run project both on the Windows an Linux environment. On linux, character is shown as "\u00" so i think this is somehow related OS problem. I've tried several things to fix the problem.
Tried to change project properties, set encoding to "UTF-8". It didn't work.
Tried to change run configuration, set encoding to "UTF-8". It didn't work.
Tried to give -Dfile.encoding="UTF-8" parameter into run parameters of Java, again it didn't work.
What is source of this problem, are transformers direclty using operating system's encoding ? Because without transformation, main json file represented as "ü", no encoding problem.
I solved this problem by changing my windows language settings to English(United Kingdom) from Turkish... Don't know how it is effected but it did the magic.

org.json JsonObject.has() returning true for key that doesn't exist

Edit - Resolved:
The issued turned out to be a combination of our logging code and how json.org handles the distinction between Javascript null and Javascript undefined. Our logging code didn't print null values in objects, so although the json object I saw had no "invoice" field, the actual input had a null "invoice" field. JSONObject's .has() method reported that there was an "invoice" field, but when I tried to access it, it's value was null so it wasn't possible to access it. Replacing the .has() check with a .isNull() check (which considers both absent fields and null values) resolved the problem.
In my Google App Engine application, we parse webhook data in the form of json and go down different code paths depending on the presence of a certain key in the json object - if $.data.object.invoice exists we do some work, otherwise we don't. However, when running in production, this detection seems to be broken. I do a simple
jsonObject.getJSONObject("data").getJSONObject("object").has("invoice")
to check for the invoice key and sometimes this returns true even when the invoice key doesn't exist. I came across this error because we do make use of the invoice value when it exists, and I was getting JSONExceptions trying to access it, even though it was protected by a has() check. I added the following logging to ensure that I was doing everything correct:
boolean isAutomaticCharge = jsonObject.getJSONObject("data").getJSONObject("object").has("invoice");
boolean doesGettingStringWork;
try {
jsonObject.getJSONObject("data").getJSONObject("object").getString("invoice");
doesGettingStringWork = true;
}
catch (JSONException e) {
doesGettingStringWork = false;
}
Logger.log("The value of automatic charge is: " + isAutomaticCharge);
Logger.log("Geting the invoice worked? " + doesGettingStringWork);
Logger.log(jsonObject.getJSONObject("data").getJSONObject("object").toString());
if (isAutomaticCharge) {
handleFailedCharge(jsonObject);
}
else {
//Manual Charge
}
And in production the following data resulted in isAutomaticCharge being true and doesGettingStringWork being false:
{
"id": "evt_16vC0s1WJGsEk3Qvnstmq6fa",
"object": "event",
"api_version": "2014-03-28",
"created": 1444678274,
"data": {
"object": {
"id": "ch_16vC0r1WJGsEk3Qv5rxezNQj",
"object": "charge",
"amount": 1900,
"amount_refunded": 0,
"captured": false,
"card": {
"id": "card_16vC0k1WJGsEk3Qvl9LLEt5K",
"object": "card",
"brand": "MasterCard",
"country": "CA",
"customer": "cus_79V0ZH6qFFA4K0",
"cvc_check": "fail",
"exp_month": 9,
"exp_year": 2016,
"fingerprint": "ifxs23sixYzpKant",
"funding": "credit",
"last4": "6912",
"metadata": {},
"name": "derek#footbole.com",
"type": "MasterCard"
},
"created": 1444678273,
"currency": "usd",
"customer": "cus_79V0ZH6qFFA4K0",
"failure_code": "card_declined",
"failure_message": "Your card was declined.",
"fraud_details": {},
"livemode": true,
"metadata": {},
"paid": false,
"refunded": false,
"refunds": [],
"source": {
"id": "card_16vC0k1WJGsEk3Qvl9LLEt5K",
"object": "card",
"brand": "MasterCard",
"country": "CA",
"customer": "cus_79V0ZH6qFFA4K0",
"cvc_check": "fail",
"exp_month": 9,
"exp_year": 2016,
"fingerprint": "ifxs23sixYzpKant",
"funding": "credit",
"last4": "6912",
"metadata": {},
"name": "derek#footbole.com",
"type": "MasterCard"
},
"status": "failed"
}
},
"livemode": true,
"pending_webhooks": 2,
"request": "req_79V0v7433eb9hZ",
"type": "charge.failed"
}
When I run the code locally and feed it that json, it works as expected with isAutomaticCharge and doesGettingStringWork both being false.
I'm running version 20140107 of org.json. I declare a new JSONObject for every request, so threading shouldn't be an issue. Has anyone else had issues running org.json on Google App Engine?

Get node details in Alfresco via back-end webscript

I want to get node details via Backend webscript but I have some issues. I've tried two webscripts:
alfresco/service/slingshot/doclib2/node/workspace/SpacesStore/a10a0777-40f4-42da-b236-8845eb26294e
alfresco/service/slingshot/doclib/node/workspace/SpacesStore/a10a0777-40f4-42da-b236-8845eb26294e.
The first one gave me this response :
{
"status" :
{
"code" : 410,
"name" : "Gone",
"description" : "Resource is no longer available at the server and no forwarding address is known."
},
"message" : "Location is 'null'. (No permission?)",
"exception" : "",
"callstack" :
[
],
"server" : "Enterprise v4.2.0 (r57217-b28) schema 6,034",
"time" : "Jun 10, 2014 10:28:15 AM"
}
and the second :
{
"status" :
{
"code" : 500,
"name" : "Internal Error",
"description" : "An error inside the HTTP server which prevented it from fulfilling the request."
},
"message" : "05100028 Wrapped Exception (with status template): 05100077 Failed to execute script 'classpath*:alfresco\/templates\/webscripts\/org\/alfresco\/slingshot\/documentlibrary\/node.get.js': 05100076 Site container UploadComponent.java does not refer to a folder.",
"exception" : "org.springframework.extensions.webscripts.WebScriptException - 05100028 Wrapped Exception (with status template): 05100077 Failed to execute script 'classpath*:alfresco\/templates\/webscripts\/org\/alfresco\/slingshot\/documentlibrary\/node.get.js': 05100076 Site container UploadComponent.java does not refer to a folder.",
"callstack" :
[
"" ,"org.alfresco.repo.site.SiteServiceException: 05100076 Site container UploadComponent.java does not refer to a folder."
,"
Updated :
You can notice that in the second webSript the error says that my file UploadComponent.java does not refer to a folder. Does this script take a cm:folder as an argument. If there is another web-script that returns the node details (properties: nodeRef, mimetype, size... ) from nodeRef please show it to me. thanks !
Pro tip - You can see all of the available web scripts at http://localhost:8080/alfresco/service/index/uri/
You're supposed to use the CMIS web scripts where possible, and this also makes for the simplest request.
http://<MyAlfresco>/alfresco/service/cmis/i/8826b8f4-9f61-41a4-9f21-14ad5b6395ab
This returns the full set of properties for the nodeRef workspace://SpacesStore/8826b8f4-9f61-41a4-9f21-14ad5b6395ab.
Some of the XML you will receive is:
<cmis:properties>
<cmis:propertyInteger propertyDefinitionId="cmis:contentStreamLength" displayName="Content Stream Length" queryName="cmis:contentStreamLength"><cmis:value>36864</cmis:value></cmis:propertyInteger>
<cmis:propertyId propertyDefinitionId="cmis:objectTypeId" displayName="Object Type Id" queryName="cmis:objectTypeId"><cmis:value>cmis:document</cmis:value></cmis:propertyId>
<cmis:propertyString propertyDefinitionId="cmis:versionSeriesCheckedOutBy" displayName="Version Series Checked Out By" queryName="cmis:versionSeriesCheckedOutBy"/>
<cmis:propertyBoolean propertyDefinitionId="cmis:isPrivateWorkingCopy" displayName="Is private working copy" queryName="cmis:isPrivateWorkingCopy"/>
<cmis:propertyId propertyDefinitionId="cmis:versionSeriesCheckedOutId" displayName="Version Series Checked Out Id" queryName="cmis:versionSeriesCheckedOutId"/>
<cmis:propertyId propertyDefinitionId="cmis:versionSeriesId" displayName="Version series id" queryName="cmis:versionSeriesId"><cmis:value>workspace://SpacesStore/8826b8f4-9f61-41a4-9f21-14ad5b6395ab</cmis:value></cmis:propertyId>
<cmis:propertyBoolean propertyDefinitionId="cmis:isLatestVersion" displayName="Is Latest Version" queryName="cmis:isLatestVersion"><cmis:value>true</cmis:value></cmis:propertyBoolean>
</cmis:properties>
I also checked and this should give you the properties for any node regardless of where it is situated in your Alfresco instance.
There are a few webscripts you can use, such as the CMIS ones, but I think the simplest is probably the Slingshot Document Library Node webscript, with ID org/alfresco/slingshot/documentlibrary/node.get. You can read about it at http://localhost:8080/alfresco/service/script/org/alfresco/slingshot/documentlibrary/node.get
For a node with noderef workspace://SpacesStore/357b6dad-d434-4a46-a7e0-731df50e5e90 the URL is http://localhost:8080/alfresco/service/slingshot/doclib/node/workspace/SpacesStore/357b6dad-d434-4a46-a7e0-731df50e5e90, and the JSON returned looks something like:
{
"metadata":
{
"parent":
{
"nodeRef": "workspace://SpacesStore/7f4e374c-7c7c-4356-bf8f-0ec6bfc5eac4",
"permissions":
{
"userAccess":
{
"permissions": true,
"edit": true,
"delete": true,
"cancel-checkout": false,
"create": true
}
}
},
"onlineEditing": true
},
"item":
{
"nodeRef": "workspace://SpacesStore/357b6dad-d434-4a46-a7e0-731df50e5e90",
"nodeType": "cm:content",
"type": "document",
"mimetype": "application\/vnd.ms-project",
"isFolder": false,
"isLink": false,
"fileName": "testPROJECT.mpx",
"displayName": "testPROJECT.mpx",
"status": "",
"title": "testPROJECT.mpx",
"description": "",
"author": "",
"createdOn": "2014-06-10T15:17:33.791+01:00",
"createdBy": "Administrator",
"createdByUser": "admin",
"modifiedOn": "2014-06-10T15:17:42.258+01:00",
"modifiedBy": "Administrator",
"modifiedByUser": "admin",
"lockedBy": "",
"lockedByUser": "",
"size": "3555",
"version": "1.0",
"contentUrl": "api/node/content/workspace/SpacesStore/357b6dad-d434-4a46-a7e0-731df50e5e90/testPROJECT.mpx",
"webdavUrl": "\/webdav\/User%20Homes\/administrator\/testPROJECT.mpx",
"actionSet": "document",
"tags": [],
"activeWorkflows": "",
"isFavourite": false,
"likes":
{
"isLiked": false,
"totalLikes": 0
},
"location":
{
"repositoryId": "8ff64edd-57d3-4198-ac3d-8386f47bf5bb",
"site": "",
"siteTitle": "",
"container": "",
"path": "\/User Homes\/administrator",
"file": "testPROJECT.mpx",
"parent":
{
"nodeRef": "workspace:\/\/SpacesStore\/7f4e374c-7c7c-4356-bf8f-0ec6bfc5eac4"
}
},
"permissions":
{
"inherited": true,
"roles":
[
"ALLOWED;administrator;All;INHERITED",
"ALLOWED;ROLE_OWNER;All;INHERITED"
],
"userAccess":
{
"permissions": true,
"edit": true,
"delete": true,
"cancel-checkout": false,
"create": true
}
},
"custom": {},
"actionLabels":
{
}
}
}
I believe that's all the metadata and properties you're after. It's a webscript used by Share, so ought to be well tested and used. As you can see from the location section, it's a webscript which works for both site-based and non-site nodes equally
(If you do hit problems with it, probably best to ensure you're running the latest service pack if on enterprise, or newest release for community)

Parsing JSON using Java/Jackson

I have a small test application I'm writing in Java to parse some JSON from the Reddit API. Some sample JSON I'm looking to parse would be like this:
[
{
"kind": "Listing",
"data": {
"modhash": "1jq62oyvwe15aaba7eb18b0b4363b567a00750766351e03dcc",
"children": [
{
"kind": "t3",
"data": {
"domain": "businessinsider.com",
"media_embed": {},
"levenshtein": null,
"subreddit": "Android",
"selftext_html": null,
"selftext": "",
"likes": null,
"saved": false,
"id": "n17u2",
"clicked": false,
"title": "CONFESSION OF A NON-APPLE-FANBOY: Even If The Samsung Galaxy Nexus Is Better, I'm Still Buying An iPhone",
"media": null,
"score": 0,
"over_18": false,
"hidden": false,
"thumbnail": "http://e.thumbs.redditmedia.com/sL0dCwGAvWqnY_sd.jpg",
"subreddit_id": "t5_2qlqh",
"author_flair_css_class": null,
"downs": 2,
"is_self": false,
"permalink": "/r/Android/comments/n17u2/confession_of_a_nonapplefanboy_even_if_the/",
"name": "t3_n17u2",
"created": 1323127132,
"url": "http://www.businessinsider.com/apple-iphone-versus-samsung-galaxy-nexus-2011-12",
"author_flair_text": null,
"author": "FormulaT",
"created_utc": 1323101932,
"num_comments": 0,
"ups": 1
}
}
],
"after": null,
"before": null
}
},
{
"kind": "Listing",
"data": {
"modhash": "1jq62oyvwe15aaba7eb18b0b4363b567a00750766351e03dcc",
"children": [],
"after": null,
"before": null
}
}
]
What I'm trying to accomplish is to get just a few values out of this JSON, e.g. the title and the author. I'm using Jackson to handle the JSON, and the code I'm using looks like this:
URLConnection conn = redditURL.openConnection();
BufferedReader buf = new BufferedReader(new InputStreamReader(conn.getInputStream()));
ObjectMapper mapper = new ObjectMapper();
RedditComment comment = mapper.readValue(buf, RedditComment.class);
Iterator itr = comment.getData().getChildren().listIterator();
I created the RedditComment and other needed classes using the JSONGen website (http://jsongen.byingtondesign.com/). However, when parsing the JSON from the BufferedReader, Jackson throws this exception:
org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of com.test.RedditAPI.RedditComment out of START_ARRAY token
at [Source: java.io.BufferedReader#3ebfbbe3; line: 1, column: 1]
at org.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:163)
at org.codehaus.jackson.map.deser.StdDeserializationContext.mappingException(StdDeserializationContext.java:219)
at org.codehaus.jackson.map.deser.StdDeserializationContext.mappingException(StdDeserializationContext.java:212)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromArray(BeanDeserializer.java:869)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:597)
at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2723)
at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1877)
at com.test.RedditAPI.main.returnRedditComment(Main.java:17)
Does anyone have any ideas? I've been scratching my head for a few hours now.
EDIT: Thanks to #Chin Boon and #Chris, I came up with the following (after switching to GSON):
Gson gson = new Gson();
List<RedditComment> comment = gson.fromJson(buf, new TypeToken<List<RedditComment>>() {}.getType());
List<RedditChildren> children = comment.get(1).getData().getChildren();
System.out.println(children.get(1).getData().getAuthor());
but that throws the following exception:
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.test.RedditAPI.RedditChildren
Apologies if I'm being a bother, I've looked around the API and there isn't any reference of LinkedHashMaps, so I don't know why it's popping up here.
The problem is that the response is an array of entries. Try:
List<RedditComment> comment = mapper.readValue(buf,new TypeReference<List<RedditComment>>(){});
if you have not already invested too much time into Jackson, may i recommend you looking at GSON, here is a tutorial that should have you started.
Google GSON API maps your JSON string into a domain object.
http://java.sg/parsing-a-json-string-into-an-object-with-gson-easily/
Also, you can use a JSON parser to see your JSON.

Categories