Get list of string from list of Json object - java

I am trying to extract list of string from following Json
"example":{[
{"#name":"name1"},
{"#name":"name2"},
{"#name":"name3"},
{"#name":"name4"}
]}
I want to get the list of #name values. I am using jayway jsonpath to do this.
I tried the following code,
List<String> response = null;
try{
ReadContext ctx = JsonPath.parse(data);
response = ctx.read(xPath);
}catch(Exception e){
AppLogger.EventLogger.error(e.getMessage());
response = null;
}
return response;
but got an exception saying could not find the specified path. I have used the following jsonPath example.#name
Can someone tell me What went wrong in my code? how to extract list #name values.
Expected output :
[name1,name2,name3,name4]

I have made small changes to your json in order to make it valid.
{"example":[
{"#name":"name1"},
{"#name":"name2"},
{"#name":"name3"},
{"#name":"name4"}
]}
and the code which specified works perfectly fine with the following expression:
$.example[*].#name
There are a lot of online services which can help validate your json.
One of them is jsonlint.com
I would also recommend to look at json.org.

Related

getJSONObject error: JSONObject["..."] is not a JSONObject

I'm trying to parse a JSON string, but getting an error when trying to get a nested object:
JSONObject jsonObject = new JSONObject(jsonString);
System.out.println(jsonObject);
System.out.println(jsonObject.keySet());
System.out.println(jsonObject.getJSONObject("matches"));
Below is the output in console. As far as I can see, the JSON is valid as jsonObject is created without an error. But when I try to obtain "matches" it throws an error. I've compared my code with tutorials but I can't see what the issue out to be:
{"matches":[{"id":233028,"awayTeam":{...
[matches, count, filters, competition]
Error in client: JSONObject["matches"] is not a JSONObject.
Anything I'm doing wrong? Happy to provide any further info if needed.
matches is an array, not an object. Use getJSONArray:
System.out.println(jsonObject.getJSONArray("matches"));
(Or more usefully:
System.out.println(Arrays.deepToString(jsonObject.getJSONArray("matches")));
since System.out.println on an array doesn't really show useful information on its own.)

Java - processing Marklogic eval response giving JSON Documents

I have a MarkLogic XQuery eval call that returns a lists of strings. I use the below code to process the results. I have another call that returns a list of Json Documents but I can't see how to get EvalResult to give me a JsonDocument document. How do I change the below code to process Json Documents?
public static ArrayList<String> getStringList(DatabaseClient client, String query)
{
ArrayList<String> strings = new ArrayList<String>();
ServerEvaluationCall eval = client.newServerEval();
EvalResultIterator eri = eval.xquery(query).eval();
while (eri.hasNext())
{
EvalResult er = eri.next();
String s = er.getString();
strings.add(s);
}
return strings;
}
First, let me suggest that you only use eval as a last resort as it may open a security hole. Injection attacks aren't possible if you never send code from the client to be executed on the server. Start first with the out-of-the-box features, and if those aren't enough, consider writing a resource extension instead of using eval. Two examples are ResourceExtension and JavascriptResourceExtension.
But to answer your question, change this:
String s = er.getString();
to this:
JacksonHandle handle = er.get(new JacksonHandle());
JsonNode json = handle.get();
or this shortcut:
JsonNode json = er.getAs(JsonNode.class);
For a complete example, see handling of myArray and myObject EvalTest.evalAndInvokeXQuery (and of course, runAndTestXQuery) and evaltest.xqy.
These Jackson handles work the same whether you're getting JSON results from a document read, search, or eval. You can read more about the io shortcuts here. For more sample code with Jackson, see JacksonHandleExample, JacksonHandleTest, JacksonStreamTest, and JacksonDatabindTest.

Decode json object to string android

I used json_encode(); to convert string to json in php and then response it to android but I can't use the response, how can I convert the json to string?
when I display the response it shows this :
"{\n'OK': \n[\n{\n'Name': 'MyName',\n'Gender':'Male'\n}\n]\n}"
what shall I do?
thank you
Since you're just converting a string to json, you're not returning a JSONObject or JSONArray, according to: http://php.net/manual/en/function.json-decode.php
If you must return a string, you may have to use some json library or write your own parser.
If that doesn't sound appealing, I recommending returning a JSONObject or JSONArray with one element.
For example:
php
echo json_encode( array('result' => 'the string you are encoding') );
java
JSONObject json = new JSONObject( encodedStringResponseFromPhp );
String theStringYouEncoded = (String) json.get( "result" );
You'll need to add a throws JSONException to the function you add this java code too or put it inside a try catch block.
Have you tried using a JSON-Library like https://code.google.com/p/json-simple/? Looks like you need some help decoding the string.
Edit: You should use the json2.js library from Douglas Crockford. It provides some extra features and better/older browser support.
Read more...

Parse serialized json payload in java

im struggling with json again :(
Here is the original response:
{"xml-fragment":{"workItem":{"#id":"251","#version":"74"},"presentation":{"#formIdenitifier":"1.0.0.201310151421/openspaceGWTPull_DefaultChannel/.default/Npda/NpdaProcess/UserReconcile/UserReconcile.gwt.json","#type":"GWT_FORM","#version":"1.0.0.201310151421","#activityName":"UserReconcile"},"workTypeDetail":{"#typePiled":"false","#pilingLimit":"0","#uid":"WT__RIoPEDWTEeOr4-yR8gXd7g","#version":"1.0.0.201310151421"},"payloadModel":{"serializedPayload":"{items:[{\"$param\":\"BankReconInput\",\"mode\":\"IN\",\"$value\":[{\"bankAccountTx_pk\":\"55213\",\"amount\":\"10099\",\"reference\":\"ImAmReference\",\"date\":\"2013-10-15\",\"reconType\":\"?\",\"amxcaseref\":\"pvm:0a12iq\",\"$type\":\"coza.npda.bom.BankTransaction\"}]}]}","#payloadMode":"JSON"}}}
i want to for example get value of amount from the serializedPayload. The problem is that it is not a json object. If i try:
obj = new JSONObject(jsonResp).getJSONObject("xml-fragment").getJSONObject("payloadModel");
this returns to me serializedPayload as a string and #payloadMode as a string.
i tried:
obj = new JSONObject(jsonResp).getJSONObject("xml-fragment").getJSONObject("payloadModel").getJSONObject("serializedPayload");
its confirms that serializedPayload is not a json object.
I looked at this example: http://developer.android.com/reference/org/json/JSONTokener.html
But its data is not as complex as mine and i am struggling to find java examples of how to do this.
Please can anyone help.
You don't need an example, you need to look at the JSON and think for a second.
serializedPayload is not a JSON object to begin with, it's really a string that has another piece of json encoded inside, sort of like the russian nesting dolls (frankly, it's an abomination).
You need to take the string, and then parse it again, using another JSONObject, sort of:
String payload = data..getJSONObject("xml-fragment").getJSONObject("payloadModel").getString("serializedPayload");
JSONObject theRealData = new JSONObject(payload);

Combination of Specific special character causes Error

When I am sending a TextEdit data as a JSON with data as a combination of "; the app fails every time.
In detail if I am entering my username as anything but password as "; the resultant JSON file looks like:-
{"UserName":"qa#1.com","Password":"\";"}
I have searched a lot, what I could understand is the resultant JSON data voilates the syntax which results in throwing Default exception. I tried to get rid of special symbol by using URLEncoder.encode() method. But now the problem is in decoding.
Any help at any step will be very grateful.
Logcat:
I/SW_HttpClient(448): sending post: {"UserName":"qa#1.com","Password":"\";"}
I/SW_HttpClient(448): HTTPResponse received in [2326ms]
I/SW_HttpClient(448): stream returned: <!DOCTYPE html PUBLIC ---- AN HTML PAGE.... A DEFAULT HANDLER>
Hi try the following code
String EMPLOYEE_SERVICE_URI = Utils.authenticate+"?UserName="+uid+"&Email="+eid+"&Password="+URLEncoder.encode(pwd,"UTF-8");
The JSON you provided in the Question is valid.
The JSON spec requires double quotes in strings to be escaped with a backslash. Read the syntax graphs here - http://www.json.org/.
If something is throwing an exception while parsing that JSON, then either the parser is buggy or the exception means something else.
I have searched a lot, what I could understand is the resultant JSON data voilates the syntax
Your understanding is incorrect.
I tried to get rid of special symbol by using URLEncoder.encode() method.
That is a mistake, and is only going to make matters worse:
The backslash SHOULD be there.
The server or whatever that processes the JSON will NOT be expecting random escaping from a completely different standard.
But now the problem is in decoding.
Exactly.
Following provided JSON can be parsed through GSON library with below code
private String sampledata = "{\"UserName\":\"qa#1.com\",\"Password\":\"\\\";\"}";
Gson g = new Gson();
g.fromJson(sampledata, sample.class);
public class sample {
public String UserName;
public String Password;
}
For decoding the text I got the solution with..
URLDecoder.decode(String, String);

Categories