Ive been sending data to a wcf webservice thats choking on complex json. When I run the debugger I can see the wcf totally ignores the incomming values and when I try to set the parameter I get Unrecognized escape sequence. How can I force the wcf to just accept the data and stop complaining like a broken old lady.
Heres my json going in that gets turned into null
{"dtTourReports":["{\"ReportedBy\":\"0101\",\"TourReportData\":[{\"ReportDataType\":\"text\",\"ReportDataTypeID\":11,\"ReportDataTypeTitle\":\"Person in Charge-Persona ancargada\",\"ReportData\":\"Jamie Andresakis\"},{\"ReportDataType\":\"bool\",\"ReportDataTypeID\":12,\"ReportDataTypeTitle\":\"Dry-Clean\",\"ReportData\":\"true\"},{\"ReportDataType\":\"bool\",\"ReportDataTypeID\":13,\"ReportDataTypeTitle\":\"Wet-Spill\",\"ReportData\":\"true\"},{\"ReportDataType\":\"bool\",\"ReportDataTypeID\":14,\"ReportDataTypeTitle\":\"Food Spill\",\"ReportData\":\"true\"},{\"ReportDataType\":\"text\",\"ReportDataTypeID\":15,\"ReportDataTypeTitle\":\"Other\",\"ReportData\":\"Test\"},{\"ReportDataType\":\"text\",\"ReportDataTypeID\":16,\"ReportDataTypeTitle\":\"Comments\",\"ReportData\":\"Test \"},{\"ReportDataType\":\"time\",\"ReportDataTypeID\":17,\"ReportDataTypeTitle\":\"Time of Inspection\",\"ReportData\":\"11-25-2013 07:29:18 PM\"}],\"localID\":1,\"TourInstanceID\":1,\"TourDetailID\":43,\"TourReportTypeID\":2,\"TourReportType\":\"Area Report\",\"TourReportComments\":\"Person in Charge-Persona ancargada: User 1<br \\\/> <br \\\/>Other: Test<br \\\/> <br \\\/>Comments: Test <br \\\/> <br \\\/>\",\"DateCreated\":\"11-25-2013 07:29:35 PM\"}"]}
This is how I ended up fixing the problem. I guess when using JSONObject's and putting them into a jsonarray you end up with extra escapes that wcf complains about.
if(cr.moveToFirst()){
reports = new JSONArray();
do{
try{
SessionData session = new SessionData(getApplicationContext());
JSONArray ja = new JSONArray(cr.getString(cr.getColumnIndex(gh._ReportData)));
JSONStringer jo = new JSONStringer().object().
key("ReportedBy").value(cr.getInt(cr.getColumnIndex(gh._CreatedBy)) != 0
? cr.getInt(cr.getColumnIndex(gh._CreatedBy)) : session.UserID_get()).
key("TourReportData").value(ja).
key("localID").value(cr.getInt(cr.getColumnIndex(gh._LocalID))).
key("TourInstanceID").value(cr.getInt(cr.getColumnIndex(gh._TourInstanceID))).
key("TourDetailID").value(cr.getInt(cr.getColumnIndex(gh._TourDetailID))).
key("TourReportTypeID").value(cr.getInt(cr.getColumnIndex(gh.GuardTourReports_ReportTypeID))).
key("TourReportType").value(cr.getString(cr.getColumnIndex(gh.GuardTourReports_ReportType))).
key("TourReportComments").value(cr.getString(cr.getColumnIndex(gh._TourReportComments))).
key("DateCreated").value(cr.getString(cr.getColumnIndex(gh._DateCreated)))
.endObject();
reports.put(jo);
}
catch(JSONException jse){
jse.printStackTrace();
return null;
}
catch(Exception e){
e.printStackTrace();
return null;
}
}while(cr.moveToNext());
Related
I am trying to figure out how to parse data that comes from Zoho CRM API inside of Android Studio. I am relatively new, but I do know how to parse data from a JSON response like this:
{
"Data": [
{ "subdata": "data"
}
]
}
Something kind of like that I can parse no problem in Android Studio, even with multiple subdata points, it's not that hard. But, I am at a complete loss when it comes to parsing data that looks like this:
{"response":{"result":{"Contacts":{"row":[{"no":"1","FL":
[{"content":"1822766000000272057","val":"CONTACTID"},
{"content":"Lisa","val":"First Name"}]},{"no":"2","FL":
[{"content":"1822766000000119148","val":"CONTACTID"},
{"content":"Eric","val":"First
Name"}]}]}},"uri":"/crm/private/json/Contacts/searchRecords"}}
Does anyone know how to parse data like this inside of Android Studio?
Update: I have a photo of what the JSON looks like in Json Viewer:
Just take it layer by layer. It can get a little verbose so I like to have a class called JSONUtils or something and use convenience methods like this to help parsing JSON without having to wrap everything in try-catch blocks:
/**
* Retrieves a json object from the passed in json object.
* #param json The json object from which the returned json object will be retrieved.
* #param key The key whose value is the json object to be returned.
* #return A json object.
* */
public static JSONObject jsonObjectFromJSONForKey(JSONObject json, String key) {
try {
return json.getJSONObject(key);
}
catch (JSONException e) {
return null;
}
}
You can make variations of this for any other data types, and by doing so you can just have your try-catch blocks in one area, and just check for null when invoking these kind of methods.
JSONObject responseJSON = JSONUtils.jsonObjectFromJSONForKey(json, "response");
if (responseJSON != null) {
JSONObject resultJSON = JSONUtils.jsonObjectFromJSONForKey(responseJSON, "result");
// So on and so forth...
}
I'm using Volley and looking at this ( http://www.androidhive.info/2014/09/android-json-parsing-using-volley/ ) tutorial, but I don't know how to make it work. Using ObjectJSON, error says "it can't be converted to Array" and if I use ArrayJSON method it doesn't found database elements.
My urlJSON - http://smkbaig.esy.es/get_info_test.php
Your JSON following the php link you provided starts with { and as the tutorial said, that's a JSON Object, followed by an array called "receptai".
If you have followed the tutorial correctly till the end, it should work using
makeJsonArrayRequest()
You really need to paste your code here so that we could help further.
What you might want to do first is follow the tutorial exactly the way it was presented, and if you get responses successfully, then start experimenting and changing. I see you are using your own JSON instead of coding for both JsonArrays and JsonObjects and seeing both buttons get functional.
Thnaks #iBobb for answer, it helped me.
Here is how it worked out:
try {
JSONArray ja = response.getJSONArray("receptai");
for (int i = 0; i < ja.length(); i++) {
JSONObject jsonObject = ja.getJSONObject(i);
rec = new Receptas();
rec.setPav(jsonObject.getString("pav"));
rec.setApras(jsonObject.getString("apras"));
rec.setIngred_sk(jsonObject.getString("ingred_sk"));
recList.add(rec);
}
// ListView
// txtResponse.setText(data);
} catch (JSONException e) {
e.printStackTrace();
}
My JSON object is like: {ids:[2079]}, but when I'm trying to get String value using
Gson gson = new GsonBuilder().setExclusionStrategies(new GsonExclusionStrategy()).create();
gson.toJson(body);
gson.toJson() is printing "{\"ids\":[2079]}", where as the expected behaviour is {\"ids\":[2079]}
I think you are double calling toJson() method which is already a String.
I mean if you call toJson() on "{ids:[2079]}", then it will produce "{\"ids\":[2079]}". So check your object.
I gone through same problem but finally i got solution.
i added commons-lang3-3.4 JAVA Library.download library
And used sample code.
String varibleString = StringEscapeUtils.unescapeJava(your JSON response string);
varibleString = varibleString .substring(1, varibleString .length() - 1);
try {
json = new JSONObject(varibleString );
}catch(Exception e)
{
e.printStackTrace();
}
StringEscapeUtils.unescapeJava(your JSON response string);
this method will help you to remove unwanted character from JSON Strting.
I had a PHP API which showed a JSON Array, which I then read into an Android Application.
I since moved servers and the android application broke.
I assumed it was the Authentication and thought I would re-build the Android application (Was my first application and thought a re-write could make things better)
For some reason I am now getting this exception error
I read somewhere that I need to parse JSON_FORCE_OBJECT in the PHP json_encode
json_encode($arrMyData, JSON_FORCE_OBJECT);
But I am running PHP 5.2 (Options parameter came out in PHP 5.3)
My code for you to rip into
private void displayAllStories(){
String line;
int intNumStories = 0;
JSONObject arrAllStories;
LinearLayout storiesLayout = (LinearLayout) findViewById(R.id.lyoutStoriesMain);
storiesLayout.removeAllViewsInLayout();
try {
while((line = this.jsonResult.readLine()) != null){
JSONObject arrStories;
arrStories = new JSONObject(line.trim());
intNumStories = Integer.parseInt(arrStories.optString("NumStories"));
arrAllStories = arrStories.getJSONObject("StoryData");
this.strDebug += "We have "+intNumStories+"\n";
}
} catch (IOException e) {
this.strDebug += "Error (3) "+e.getLocalizedMessage()+"\n";
} catch (JSONException e) {
this.strDebug += "Error (4) "+e.getLocalizedMessage()+"\n";
}
}
And the encoded data from the website
{
"NumStories":1,
"StoryData":{
"Story0":{
"ID":"1020",
"OWERNAME":"Alicia",
"STORYMAIN":"Good evening my son was born with bilateral club feet. When he was a week old we started serial casting once a week for 3 months and then he was placed in braces for the next 6 months for a 23 hour period and then for the next 3 months just durning the night. This last visit the doctor said that he needs to have his tendons lengthened and he will go back into cast. After reading all of these articles I am a little scared on what will be best for him. It sounds like the risk of having the surgery are just as heavily weighed as just keeping him in AFO\\'s till he can make his own decision. I would like all advice whether it be positive or negative. Thank you in advance for your help.",
"STORYBRIEF":"Need reassurance that tendon lengthening is the best decision.",
"ADDEDDATE":"2011-12-12 00:51:16",
"CURRENTSTATUS":"n"
}
}
}
Sorry I should add, the code before this which procudes jsonResult is as follows
try{
URL url = null;
URLConnection urlConn = null;
InputStreamReader jsonIsr = null;
BufferedReader jsonBr = null;
//this.strDebug += "URL is "+this.strURL+"\n";
url = new URL(this.strURL);
urlConn = url.openConnection();
jsonIsr = new InputStreamReader(urlConn.getInputStream());
jsonBr = new BufferedReader(jsonIsr, 8192);
this.jsonResult = jsonBr;
return true;
}catch(MalformedURLException e){
this.strDebug += "JSON Error (1) "+e.getLocalizedMessage()+"\n";
}catch(IOException e){
this.strDebug += "JSON Error (2) "+e.getLocalizedMessage()+"\n";
}
}else{
strDebug = "NO URL Passed to JSON\n";
}
// EDIT 2
For those who asking
The error is as the title says
Error (4) A JSONObject text must being with '{' at character 1 of {"NumStories":1, "StoryData":........
Your code assumes that whole JSON data comes on one line: it iterates with readLine() but creates a new JSON object every time.
You are reading the data line by line and trying to convert each line into a JSON object. That won't work because a single line just contains a fragment of a complete JSON object.
I don't know what type jsonResult has. But you'll probably want to read the whole thing at once.
Your old web application probably produced JSON data without line break so a single line would contain a full JSON object.
i think you read the json file line by line and pass to the json object you should like this way the whole string you have to pass to the json object for parsing than only you getting the json
JSONObject arrStories = new JSONObject(jsonResult);
now get the object like this way
intNumStories = Integer.parseInt(arrStories.getString("NumStories"));
This code is going to break, if object takes more than one line (apparemtly it does). Your choices are:
Collect all the strings into string builder, the parse from this string ( http://developer.android.com/reference/org/json/JSONTokener.html )
Take GSON or my databinding layer ( https://github.com/ko5tik/jsonserializer ) and just parse stream into object.
There are some pdf files in my d drive.In my android application I have to return the list of files from a servlet to my activity class,but through my codes it is returning the name of all files as a string.But i need each name separetly.How to do that,
You a using HTTP to pass data from your servlet to your Android application. HTTP doesn't care about the content of the response, so there is no standard way of defining the structure of the data you are passing. You are pretty much free to do as you please.
One option therefore would be to put your filenames into a comma-separated list in the servlet. In your Android application you chop the String apart into an array of Strings each representing one file name:
String[] filenames;
filenames = responseString.split(",");
That's the easy way. You could also create XML from your filenames in your servlet, and parse the XML in your Android application. That would look nicer, but it is more work.
Use JSONObject
JSONObject jsEmployeeObj = new JSONObject();
JSONArray empArray = new JSONArray();
while (condition) {
JSONObject jsObject = new JSONObject();
jsObject.accumulate("name", res.getString("name"));
empArray.add(jsObject);
}
if ((empArray != null) && (empArray.size() > 0)) {
jsEmployeeObj.accumulate("employeeList", empArray);
} else {
jsEmployeeObj.accumulate("employeeList", "empty");
}
String output = jsEmployeeObj.toString();
return the string ... u can parse JSON in android