I'm scanning single letters and numbers. All the numbers should be parsed into numbers[]. But it's always catching the exception. For Example: result is "3" but I can't parse it for some reason. I also tried to check if it's actually "3" with an if statement but I also got a false returned. Can someone explain me why it isn't working?
File imageFile = new File("C:\\Users\\Nils\\IdeaProjects\\untitled8\\Images\\Cutted\\"+i+m+".png");
ITesseract instance = new Tesseract(); // JNA Interface Mapping
// ITesseract instance = new Tesseract1(); // JNA Direct Mapping
instance.setDatapath("C:/Users/Nils/Desktop/blum/Tess4J/tessdata"); // path to tessdata directory
try {
String result = instance.doOCR(imageFile);
try {
resultI=Integer.parseInt(result);
numbers[0] = resultI;
}catch (NumberFormatException e){
numbers[0]=0;
}
} catch (TesseractException e) {
System.err.println(e.getMessage());
}
Ok I figured it out.
if(result.length()>1)
result=result.substring(0,1);
Delets everything that caused errors but keeps the number I want to separate.
I need to read a .json file and change a field in runtime.
The problem is when I try to read it:
JSONObject jOb=null;
try {
jOb = new JSONObject(filePath);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(jOb.toString());
try {
jOb.put("responseType", "TESTicles");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(""+jOb);
I get the following error: "A JSONObject text must begin with '{' at 1 [character 2 line 1]"
I think the problem might be the BOM marker because my file starts with '{'
Here's a sample (the beginning of my json file):
{
"base":{
"sites":{
"local":{
"name":"siteA",
"datasource":{
...
I need to remove the BOM marker in order to read the file but how can I do it without reading the file?
I've read:
This, this and many other stuff about it, but I can't seem to find any solution to my problem. What can I do?
On the assumption that you are using the library defined at json.org, what your code does is treat the file name as a JSON string and try to interpret it as a JSON object.
Reading the docs, you'll need to open the file as an input stream, pass it as a parameter in a JSONTokener constructor which you pass as a parameter to your JSONObject constructor, something like:
InputStream foo = new FileInputStream(filePath);
JSONTokener t = new JSONTokener(foo);
JSONObject obj = new JSONObject(t);
Note: the above not tested or even compiled.
I'm trying to send a JSON object which contains a JSON array with JSON objects inside via HTTP POST parameters.
The format of the parameter (what the server expects) is something like:
{""team"":[
{""teamid"":""179228"",""position"":1},
{""teamid"":""218036"",""position"":2},
{""teamid"":""88109"",""position"":3},
{""teamid"":""88111"",""position"":4},
{""teamid"":""165536"",""position"":5},
{""teamid"":""224645"",""position"":6}
]}
nevertheless, what gets sent is:
{"team":"[
\"{\\\"position\\\":0,\\\"teamid\\\":\\\"88107\\\"}\",\"{\\\"position\\\":1,\\\"teamid\\\":\\\"88109\\\"}\",\"{\\\"position\\\":2,\\\"teamid\\\":\\\"156714\\\"}\",\"{\\\"position\\\":3,\\\"teamid\\\":\\\"138877\\\"}\",\"{\\\"position\\\":4,\\\"teamid\\\":\\\"168730\\\"}\",\"{\\\"position\\\":5,\\\"teamid\\\":\\\"88110\\\"}\",\"{\\\"position\\\":6,\\\"teamid\\\":\\\"88111\\\"}\",\"{\\\"position\\\":7,\\\"teamid\\\":\\\"134431\\\"}\",\"{\\\"position\\\":8,\\\"teamid\\\":\\\"88112\\\"}\",\"{\\\"position\\\":9,\\\"teamid\\\":\\\"138507\\\"}\",\"{\\\"position\\\":10,\\\"teamid\\\":\\\"138880\\\"}\",\"{\\\"position\\\":11,\\\"teamid\\\":\\\"138881\\\"}\",\"{\\\"position\\\":12,\\\"teamid\\\":\\\"151465\\\"}\",\"{\\\"position\\\":13,\\\"teamid\\\":\\\"151464\\\"}\
"]"}
The way I build that JSON object is the following:
JSONArray teamArray = new JSONArray();
JSONObject jsonRoot = new JSONObject();
for (int i = 0; i < mTeams.size(); i++) {
String teamId = null;
BaseModel data = mTeams.get(i);
if (data != null && data instanceof TeamModel) {
teamId = ((TeamModel) data).getId();
}
JSONObject teamObject = new JSONObject();
try {
teamObject.put(
getResources().getString(
R.string.sendResortedTeamsPosition), i);
teamObject.put(
getResources().getString(
R.string.sendResortedTeamsTeamId), teamId);
teamArray.put(teamObject);
} catch (NotFoundException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
try {
jsonRoot.put("team", teamArray);
mNameValuePairs.put("teams", jsonRoot);
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
In the last but one line (jsonRoot.put("team", teamArray);) it has the same format as what gets sent in the last line, but with one less \, so one less times "parsed" apparently.
Part of my HTTP code:
String postBody = json.toString();
Log.d("HTTPHelper", "posting JSON: " + postBody);
((HttpPost) httpRequest).setEntity(new StringEntity(postBody));
Why is this happening? Is it Java?
Any ideas how could I build the correct JSON? or any work around?
Thanks a lot in advance!
I gave this up, and decided to go the dirty-way: replacing chars manually the following way:
json = new JSONObject(nameValuePairs.toString().replace("\"", "'"));
json = new JSONObject(json.toString().replace("\"", ""));
It's ugly, probably dangerous or risky, but it works...
Too much code for this task, checkout this library https://github.com/kodart/Httpzoid
It uses GSON internally and provides API that works with objects. All JSON details are hidden.
Http http = HttpFactory.create(context);
http.get("http://example.com/users")
.handler(new ResponseHandler<User[]>() {
#Override
public void success(User[] users, HttpResponse response) {
}
}).execute();
just a tip... i'm not really into android, just java..
but you could de- and encode your json with Base64 on both sides, and pass the encoded "String".
so you don't have to worry about any "dirty-way" replacing.
hope this helps u or others, too. :)
So I currently store a bunch of string titles together into a file on the user's phone and then read it later (when they relaunch the app). I'm trying to read back the string and split it on the delimiter I set for it but for some reason it splits it and then doubles the string...
So for example if I stored these strings
Ricky(har)Bobby(har)is(har)cool(har)
(har) is the delimiter I use to store them. (for example)
For some reason, when I use the split function on "har"
It gives me an array of strings, but doubles how many I stored... So the array of strings would have two Ricky's two Bobby's two is's and two cool's.
I'm at a loss for what's going on to be honest. Been staring at this for hours... anyone have any idea?
line = BR.readLine();
String[] each = line.split("<TAG>");
for (int i = 0; i < each.length; i++) {
listOfCourses.add((each[i]));
//Toast.makeText(context, each[i], Toast.LENGTH_SHORT).show();
}
Here's the function that stores the data to the user's phone
//adds data into the classes file on user's phone
public void addClassesIntoFile(Context context, ArrayList<String> classList) {
try {
FileOutputStream fos = context.openFileOutput(CLASSLIST_FILENAME,
Context.MODE_PRIVATE | Context.MODE_APPEND);
OutputStreamWriter osw = new OutputStreamWriter(fos);
for (int i = 0; i < classList.size(); i++) {
osw.write(classList.get(i) + "<TAG>");
}
osw.flush();
osw.close();
} catch (FileNotFoundException e) {
// catch errors opening file
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I don't believe your split function is the problem and instead think it's with some other part of your code.
Is the String before you conduct the split correct? Or do you see duplications in it?
I imagine the problem is with your addClassIntoFile method. Since you are appending into the File, be sure you aren't re-adding values that are already there. Unless you delete that file at some point, it'll persist the next time the app is launched.
Finally make sure you aren't calling addClassIntoFile more then you meant too. IE, accidentally invoking it more then once on a given object.
If I'm incorrect on all this, then please post an example of what the String looks like before a split so we can be sure the given regex is correct.
Replace:
String[] each = line.split("<TAG>")`
with this:
String[] each= line.split("[(har)]");
if the wrong still, tell me please
IN json object if we can found if data exist by jsonobj.has("element_name") by how can we check that data is jsonarray or json object, follow error gives error if only one events element found and throws JSONexception.
JsonObject jObj;
if (json.has("Events")) {
try {
JSONArray eventsArray = json.getJSONObject("Events");
} catch (JSONException e) {
jObj = json.getJsonObject(""Events"")
}
}
Is there a reason you're trying to read an array using getJSONObject instead of getJSONArray?
If it's possible that the Events array doesn't always exist, you should be using the optJSONArray method.
If it's a different problem, you'd need to post some example JSON for the success and failure cases to make your question clearer.