Can't receive proper format of String from JSON - java

I'm trying to read my .json file in .jsp file. The text I want to read is (from polish): "wewnętrzny". Instead of it I receive something like: "wewn�?trzny".
The code I'm using seems to not be working:
try {
JSONObject jsonObject = (JSONObject) parser.parse(new FileReader(FILE_PATH));
JSONArray tab = (JSONArray) jsonObject.get("tab");
for (int i = 0; i < tab.size(); i++) {
JSONObject jsonObjectRow = (JSONObject) tab.get(i);
byte[] raw = jsonObjectRow.get("a").toString().getBytes(ISO_8859_1);
String a = new String(raw, UTF_8);
out.println(a);
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
I've tried several encodings and all the solutions from: https://www.baeldung.com/java-string-encode-utf-8. Unfortunatelly, nothing made it work properly.
How can I fix this issue?

Ok, I figured it out!
In code it should be only:
String a = jsonObjectRow.get("a").toString();
And the file should be saved in windows-1250 encoding!
Thank's #marcinj for your advice!

Related

How to convert JSON array to Java String array

I have a php file which fetches all rows from a specific column. The result is then put into an array and then json_encoded. When I Toast the output from the php file it shows a JSON string with the correct values. I need to convert this to a Java String array so I can iterate through it one by one on a button click.
I've tried multiple solutions on here but to no avail so any help will be greatly appreciated!
getImage.php
$sql = "SELECT advert_File_Path FROM Ads";
$result = $mysql_con->query($sql) or die('Query problem: '.mysqli_error($mysql_con));
//create array
$resultarray = array();
while($row = mysqli_fetch_assoc($result)){
$resultarray[] = $row;
}
echo json_encode($resultarray);
MainActivity.java (only the code that is relevant)
private void loadNextAdvert()
{
Toast.makeText(this, "Please wait, image may take a few seconds to load...", Toast.LENGTH_LONG).show();
dbhelper = (DbHelper) new DbHelper(new DbHelper.AsyncResponse() {
#Override
public void processFinish(String output) {
if(output.equalsIgnoreCase("exception") || output.equalsIgnoreCase("unsuccessful")){
Toast.makeText(MainActivity.this, "Connection error", Toast.LENGTH_SHORT).show();
}else{
//initializes ArrayList
stringList = new ArrayList<>();
try {
//initializes JSONArray with output from php getImage file
jsonArray = new JSONArray(output);
if(jsonArray != null){
int len = jsonArray.length();
for(int i=0; i<len; i++){
stringList.add(jsonArray.get(i).toString());
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(MainActivity.this, String.valueOf(stringList), Toast.LENGTH_LONG).show();
}
}
}).execute(loadPic);
}
The Toast which should display the contents of the ArrayList just appears as '[]'.
Managed to solve it myself. So here goes,
Step 1. I had to remove commented code from my php file as it was breaking through somehow, thats where the came from at the end of the JSON array.
Step 2. I had to remove an additional echo from the php file which I was using for error checking. I think I'm right in saying the only echo you want to have is the json_encode.
Step 3. Checked the length of JSONarray in Java and it was logging 5 so I now knew it was reading correctly.
Step 4. Added Pavneet_Singh's code snippet to replace stringList.add(jsonArray.get(i).toString());
with stringList.add(jsonArray.getJSONObject(i).optString("advert_File_Path"));
Step 5. Converted stringList from an ArrayList to a String array using this code stringArray = new String[stringList.size()];
stringArray = stringList.toArray(stringArray);
Happy days! I've spent far too long trying to figure this out haha the first two steps are pretty noobish but it's sometimes the most obvious things in life that are the hardest to find. Hopefully this can help someone else too!
use stringList.add(jsonArray.getString(i));
Try this:
JSONArray arr = new JSONArray(putNesessaryValueHere);
List<String> list = new ArrayList<String>();
for(int i = 0; i < arr.length(); i++){
list.add(arr.getJSONObject(i).getString("name"));
}
Try this :
ArrayList<String> arrayList = new ArrayList<String>();
JSONArray jsonArray = new JSONArray();
for(int i = 0, count = jsonArray.length(); i< count; i++)
{
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
arrayList.add(jsonObject.toString());
}
catch (JSONException e) {
e.printStackTrace();
}
}

Why do I have 98 lines instead of 99?

I have a directory named json which contains 99 json files.
The files are named: sentiment_i.json where i is an incremental integer starting from 1.
I wrote some code to read some content from each of these files and write said content in a txt file with one line for each json file.
public static void main(String[] args) throws Exception, IOException, ParseException {
String type ="";
ArrayList<String> sentiment = new ArrayList<String>();
int i= 1;
double score = 0;
File dir = new File("json");
File[] directoryListing = dir.listFiles();
JSONObject jsonObject;
if (directoryListing != null) {
for (File child : directoryListing) {
JSONParser parser = new JSONParser();
try {
jsonObject = (JSONObject) parser.parse(new FileReader("json/sentiment_"+i+".json"));
} catch (FileNotFoundException e) {
i++;
continue;
}
JSONObject doc = (JSONObject) jsonObject.get("docSentiment"); // get the nested object first
type = (String)doc.get("type"); // get a string from the nested object
// CODICE PER PRENDERE ANCHE LO SCORE
if (!(type.equals("neutral"))){
score = (double) doc.get("score");
} else score = 0;
sentiment.add(type+";"+score);
i++;
}
}
PrintWriter out = new PrintWriter("sentiment.txt");
for(String value: sentiment)
out.println(value);
out.close();
}
}
The problem is that I get 98 lines in my txt file even if there are 99 json files in the directory.
I've been trying to find the bug for an hour now but I'm going nuts!
Hope you can help me, thanks.
EDIT: Woah the downvotes :(
Anyway, maybe I was not clear. The point has never been catching and dealing with the missing file!
Also
jsonObject = (JSONObject) parser.parse(new FileReader(child))
in my case is not useful at all and let me explain why.
In the json folder, as stated, there json files named like this: "sentiment_1", "sentiment_2" and so on.
In the folder there are let's say 1000 of these but not every number from 1 to 1000 is there.
If you rely on FileReader(child), in the for loop the files are not read in the correct order (1,2,3,4...)!
This happens because for the sorting order in the folder, for example 10 comes before than 2 because the order is 1,10,2,3,4....
So, as clearly the downvoters didn't understand at all, the problem is not that easy at it seems.
It's not about a simple loop problem lol.
Because of this block of code:
try {
jsonObject = (JSONObject) parser.parse(new FileReader("json/sentiment_"+i+".json"));
} catch (FileNotFoundException e) {
i++;
continue;
}
Which is omitting the error from you, use this instead:
try {
jsonObject = (JSONObject) parser.parse(new FileReader("json/sentiment_"+i+".json"));
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
I believe you have a missformatted json file name:
try {
jsonObject = (JSONObject) parser.parse(new FileReader("json/sentiment_"+i+".json"));
} catch (FileNotFoundException e) {
i++;
continue;
}
This block of code tells that, if a file is not found, it is just ignored without any console feedback.
Replace by :
try {
jsonObject = (JSONObject) parser.parse(new FileReader("json/sentiment_"+i+".json"));
} catch (FileNotFoundException e) {
System.out.println("Missing json file: " + e.getMessage());
i++;
continue;
}
You will have an idea about what is going on.
A better solution
Currently you are looping through files but you never use the current iteration, you are using an i variable. A FileReader can be instanciated with a File instead of the file path as a string:
try {
jsonObject = (JSONObject) parser.parse(new FileReader(child));
} catch (FileNotFoundException e) {
System.out.println("Missing json file: " + e.getMessage());
i++;
continue;
}

How to read a JSON file from Assests folder instead of URL in Volley

I have a JSON file in the assets folder. I'd like to read this file and do something with the data. How can I use Volley for this? I can't find anything like this. I don't want to use more libraries like gson or jackson.
Can I handle it with just Volley?
Thanks a Lot.
You dont need volley to read a Json file from the asset directory.
In my case, I load an array of Json from the file into my string "filePath".
final String filePath = readFromAsset(act, "json_to_load.json"); //act is my current activity
try {
JSONArray obj = new JSONArray(filePath);
for (int i = 0; i < obj.length(); i++) {
JSONObject jo = obj.getJSONObject(i);
// do stuff
}
} catch (JSONException e) {
e.printStackTrace();
}
In my utils file :
private static String readFromAsset(Activity act, String fileName)
{
String text = "";
try {
InputStream is = act.getAssets().open(fileName);
int size = is.available();
// Read the entire asset into a local byte buffer.
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
text = new String(buffer);
} catch (IOException e) {
e.printStackTrace();
}
return text;
}
To be able to use it your have to import the package "org.json;".
Hope it helps !
Volley itself is not able to parse JSON, so you need to use GSON or ...

How to get value from JSON in Android

I have JSON response:
{"error":100,"result":"{\"distance\":2.4,\"duration\":5,\"price\":0}"}
From this response I want to get a "distance" value for example. How to do it?
I tried to do like this:
String distance = String.valueOf(finalResponseDataJOSNObject.getDouble("distance"));
but string value is null. Any ideas?
UPDATE:
Finally we discovered that it was back-end issue and we fixed it. No additional operations like JSONObject conversation to String, special character removal, etc. was necessary.
Simply:
String distance =
String.valueOf(finalResponseDataJOSNObject.getJSONObject("result").getDouble("di‌​stance"));
Try this...
String json = "{\"error\":100,\"result\":{\"distance\":2.4,\"duration\":5,\"price\":0}}";
try {
JSONObject jsonObject = new JSONObject(json);
double distance = jsonObject.getJSONObject("result").getDouble(
"distance");
Log.i("DISTANCE", String.valueOf(distance));
} catch (JSONException e) {
e.printStackTrace();
}
The distance is in a JSONObject under result only. So you have to getJSONObject("result").getDouble("distance").
You can do this in following way:
Remove special character from json string and convert back to json object and process it accordingly:
String json = "{\"error\":100,\"result\":{\"distance\":2.4,\"duration\":5,\"price\":0}}";
try{
JSONObject jsonObject = new JSONObject(json.replaceAll("\"", ""));
JSONObject jsonObject2=jsonObject.getJSONObject("result");
String distance=jsonObject2.getString("distance");
double convertedDistance=Double.valueOf(distance);
Log.i("DistanceInformation", "My Distance from json is="+distance);
}catch(JSONException e)
{
e.printStackTrace();
}
Thanks for you all who responded.
Finally we discovered that it was back-end issue and we fixed it. No additional operations like JSONObject conversation to String, special character removal, etc. was necessary.
Simply:
String distance =
String.valueOf(finalResponseDataJOSNObject.getJSONObject("result").getDouble("di‌​stance"));

HTTPResponse as JSON in Java

I was trying to get an JSONObject from a HTTP response.
try
{
GetMethod postMethod = new GetMethod();
postMethod.setURI(new URI(url, true));
postMethod.setRequestHeader("Accept", "application/json");
httpClient.executeMethod(postMethod);
String resp=postMethod.getResponseBodyAsString();
org.json.JSONTokener tokener = new org.json.JSONTokener(resp);
finalResult = new org.json.JSONArray(tokener);
return finalResult;
}
But I got a runtime warning as
Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.
Should I get the response as stream as suggested by the JVM ? If so, how could I parse the JSON from it ?
Has your server been set up to inform clients how big its responses are? If not, your server is streaming the data, and it's technically impossible to tell how much buffer space is required to deal with the response, warranting a warning that something potentially dangerous is going on.
if you want to send jsonObjects from server suppose (tomcat server)
For server side-
creating jsonobjects-
I have Called toJson() for creating jsonobjects this is the implementation-
final JSONObject arr = new JSONObject();
for (int i = 0; i < contactStatus.size(); i++) {
ContactStatus contactObject = contactStatus.get(i);
try {
arr.put(String.valueOf(i), toJson(value1, value2,, value3));
} catch (JSONException e) {
catch block e.printStackTrace();
}
}
//Here we serialize the stream to a String.
final String output = arr.toString();
response.setContentLength(output.length());
out.print(output);//out is object of servlet output stream.
public static Object toJsonForContact(String value1, boolean value2, double value3) throws JSONException {
JSONObject contactObject = new JSONObject();
contactObject.put("id", id);
contactObject.put("status", value1);
contactObject.put("distance", value2);
contactObject.put("relation", value3);
return contactObject;
}
so your jsonobjects are ready for sending we write these objects to ServletoutputStream.
in client side-
while ((ReadResponses = in.readLine()) != null) {
Constants.Response_From_server = ReadResponses;
if (Constants.Response_From_server.startsWith("{")) {
ListOfContactStatus = new ArrayList<ContactStatus>();
ContactStatus contactStatusObject;
try {
JSONObject json = new JSONObject(Constants.Response_From_server);
for (int i = 0; i < json.length(); i++) {
contactStatusObject = new ContactStatus();
JSONObject json1 = json.getJSONObject(String.valueOf(i));
System.out.println("" + json1.getString("id"));
System.out.println("" + json1.getBoolean("status"));
System.out.println("" + json1.getDouble("distance"));
contactStatusObject.setId(json1.getString("id"));
contactStatusObject.setStatus(json1.getBoolean("status"));
contactStatusObject.setDistance((float) json1.getDouble("distance"));
ListOfContactStatus.add(contactStatusObject);
System.out.println("HTTPTransport:sendMessage Size of ListOfContactStatus" + ListOfContactStatus.size());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
You can easily generate JSonObject usin Java EE 7. The sample code.
JsonReader reader = Json.createReader(new URI(url, true));
JsonObject jsonObject=reader.readObject();
For details information go through to the link.
http://docs.oracle.com/javaee/7/tutorial/doc/jsonp003.htm#BABHAHIA

Categories

Resources