Java - How can I parse multiple JSON objects in Jackson? - java

I'm trying to parse multiple objects from a REST response. They initially get returned as JSON Lines (jsonl file format). i.e.:
{"AccountId":"123","Name":"Jeff"}
{"AccountId":"456","Name":"Joe"}
{"AccountId":"789","Name":"John"}
The first thing I do is convert it to a string:
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.com", 8080));
HttpsURLConnection httpsCon = (HttpsURLConnection) (new URL(url)).openConnection(proxy);
InputStream inputStream = httpsCon.getInputStream();
Reader reader = new InputStreamReader(inputStream);
char[] arr = new char[8 * 1024];
StringBuilder buffer = new StringBuilder();
int numCharsRead;
while ((numCharsRead = reader.read(arr, 0, arr.length)) != -1) {
buffer.append(arr, 0, numCharsRead);
}
reader.close();
return buffer.toString();
But I get errors trying to parse the String it as it's not JSON structure. So I've used a regex to format the objects into JSON structure.
{"AccountId":"123","Name":"Jeff"},{"AccountId":"456","Name":"Joe"},{"AccountId":"789","Name":"John"}
What I've tried so far:
JSONArray dataArr = new JSONArray(newTargetString);
Results in: type org.json.JSONObject cannot be converted to JSONArray
JSONObject dataObj = new JSONObject(newTargetString);
Results in a single object getting parsed instead of all 3.

Related

String to JSONArray returns null for some reason

I have a URL that retuns a JSON back and I first convert it to String and then convert it to JSONArray but for some reason, it's returning null.
The sample url looks like this:
https://data.phila.gov/resource/sspu-uyfa.json?dispatch_date=2017-08-01
Below is my code:
public JSONArray getJsonFromUrl(final String data_url) throws IOException, JSONException {
InputStream is = new URL(data_url).openStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
is.close();
JSONArray jsonArray = new JSONArray(sb.toString());
return jsonArray;
}
So the StringBuilder object sb is not null. When I debug, I can see it is a huge string. But it's new JSON(sb.toString()); that returns null. Also, I tried replacing JSONArray with JSONObject and still same issue.
Any help would be appreciated!
your data has a SyntaxError. in near column 48697,
H have find the bad data segment:
,"ucr_gen1447C3FA9C2915241",
I think you would like :
,"ucr_general":"1447C3FA9C2915241",

Parsing JSON Object from a JSON array

I am currently developing an app and need to parse JSON objects from inside an unnamed array.
I can only manage to parse JSON arrays with a name such as this one: http://jsonparsing.parseapp.com/jsonData/moviesDemoItem.txt.
The code that I used for the one above is
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String asd = buffer.toString();
JSONObject parentObject = new JSONObject(asd);
JSONArray parentArray = parentObject.getJSONArray("movies");
JSONObject fObject = parentArray.getJSONObject(0);
String movie = fObject.getString("movie");
int year = fObject.getInt("year");
return movie + year;
The code includes "movies" which is the array name .
What should I change to parse only the objects from within a JSON array such as https://restcountries.eu/rest/v1/all?
Your countries list is simply an array. Doesn't need a name.
Simply replace
JSONObject parentObject = new JSONObject(asd);
with
JSONArray parentObject = new JSONArray(asd);
See this post for how to iterate over that array to parse the remainder of the objects.
How to parse JSON in Android
Starting something like
for (int i=0; i < parentObject.length(); i++) {
Alternatively, Volley's JsonArrayRequest would be useful, or learning about Retrofit+Gson would be even better if you don't feel like manually parsing the JSON data yourself.

Incorrect Json String was received on client while it was generated correctly on server side

I am working on a Server-Client application. For part of the requests, I need to generate a piece of Json String on Server side and send it to Client. The Json String was generated correctly on the server side according to the Server log. But on the Android client side, the String was changed and cannot be parsed as correct Json String.
Here are some related code.
Generate Json String on Server side:
#RequestMapping(value="/resourceList/{actType}/{type}/{id}")
#ResponseBody public Object personList(#PathVariable int actType, #PathVariable int type, #PathVariable int id){
ArrayList<ItemBase> list = new ArrayList();
......
return new ArrayList();
}
This generates following Json code:
[{"countryID":1,"locationID":5,"siteID":5,"brief":"shark point","userID":0,"status":"normal","rank":0.0,"id":2,"timestamp":1471494991000,"displayName":"shark point","pic":"2.jpg","actType":1,"type":64},{"countryID":1,"locationID":5,"siteID":5,"brief":"halik","userID":0,"status":"normal","rank":0.0,"id":3,"timestamp":1471495034000,"displayName":"halik","pic":"3.jpg","actType":1,"type":64}]
And receive it on Android client:
......
HttpURLConnection urlConnection = null;
try {
URL url = new URL(request);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
byte[] buffer = new byte[256];
int len = 0;
StringBuilder responseBuilder = new StringBuilder();
while ((len = in.read(buffer)) != -1) {
String str = new String(buffer, "utf-8");
responseBuilder.append(str);
}
String response = responseBuilder.toString().trim();
The response variable was written with value:
[{"countryID":1,"locationID":5,"siteID":5,"brief":"halik","userID":0,"status":"normal","rank":0.0,"id":3,"timestamp":1471495034000,"displayName":"halik","pic":"3.jpg","actType":1,471494991000,"displayName":"shark point","pic":"2.jpg","actType":1,"type":64},{"countryID":1,"locationID":5,"siteID":5,"brief":"halik","userID":0,"status":"normal","rank":0.0,"id":3,"timestamp":1471495034000,""type":64}]":"halik","pic":"3.jpg","actType":1,471494991000,"displayName":"shark point","pic":"2.jpg","actType":1,"type":64},{"countryID":1,"locationID":5,"siteID":5,"brief":"halik","userID":0,"status":"normal","rank":0.0,"id":3,"timestamp":1471495034000,"
Which cannot be parsed as Json String correctly with obvious errors.
Most methods which return a Json String to client request work fine as I expected except this one. But this method was implemented almost exactly the same as those ones work correctly. Thus I have no idea how this happened at all. Any one got any clew please help.
You're building String the wrong way.
Try this instead:
// …
HttpURLConnection urlConnection = null;
try {
URL url = new URL(request);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedInputStream bis = new BufferedInputStream(in);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int result = bis.read();
while(result != -1) {
buf.write((byte) result);
result = bis.read();
}
String response = buf.toString();
// …

BufferedReader to Jsonarray in android

I have a jsonFile in this format.
[{"KeyTokenName":"Safe 2","UntilTime":"16:39","FromTime":"16:39","FromDate":"2015\/04\/10","Count":8,"KeyRingId":1,"UntilDate":"2016\/04\/10"}]
[{"KeyTokenName":"Safe 1","UntilTime":"16:40","FromTime":"16:40","FromDate":"2015\/04\/10","Count":15,"KeyRingId":1,"UntilDate":"2016\/04\/10"}]
[{"KeyTokenName":"Safe 1","UntilTime":"16:42","FromTime":"16:42","FromDate":"2015\/04\/10","Count":25,"KeyRingId":1,"UntilDate":"2016\/04\/10"}]
I am trying to read from the json file using this code.
FileInputStream inputStream = new FileInputStream(new File(path));
BufferedInputStream bis = new BufferedInputStream(inputStream);
StringBuffer b = new StringBuffer();
while (bis.available() != 0) {
char c = (char) bis.read();
b.append(c);
}
bis.close();
inputStream.close();
JSONArray data = new JSONArray(b.toString());
But I In data object I only get the content of the first object from the json file that is
[{"KeyTokenName":"Safe 2","FromDate":"2015\/04\/10","FromTime":"16:39","UntilTime":"16:39","Count":8,"UntilDate":"2016\/04\/10","KeyRingId":1}]
But I want all the content to be in there is the Json array object. What needs to be done. I don't want to use any external libraries for Json parsing.
Please help.
Why you don't use some existing solutions that allow you to do mapping of java class to json and vice versa like Gson library?

Decoding HttpEntity into android string - encoding issue

I know that should be basics but i had no formation :( and I don't understand it, everywhere it seems obvious to people. I get that one side encode data with his set and android is probably expecting another one, but what can I do to translate?
My app perform a get request on google maps api to retrieve an address from a Lat/lng. But I failed to decode properly the result as a French è is displayed as è
I have not enough xp in Java to understand what to do. It is linked with UTF-8, right?
What should I do?
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
JSONObject jsonObject = new JSONObject();
jsonObject = new JSONObject(stringBuilder.toString());
retList = new ArrayList<Address>();
if("OK".equalsIgnoreCase(jsonObject.getString("status"))){
JSONArray results = jsonObject.getJSONArray("results");
for (int i=0;i<results.length();i++ ) {
JSONObject result = results.getJSONObject(i);
String indiStr = result.getString("formatted_address");
Address addr = new Address(Locale.ITALY);
addr.setAddressLine(0, indiStr);
Dbg.d(TAG, "adresse :"+addr.toString());
retList.add(addr);
}
}
Thanks for help !
Try using UTF-8,
instead of using InputStream try something like,
String responseBody = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
you can use BufferReader
your code will be like this:
InputStream stream = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
int b;
while ((b = br.read()) != -1) {
stringBuilder.append(b);
}

Categories