Convert a .json file to a JSONArray - java

I used cURL to get some twitter feeds in the form of a json file ("twitter-feed.json"). I want to convert this json file to a JSONArray object. How do I do it?
I am new to Java and json. Your suggestions are most welcome.
FileInputStream infile = new FileInputStream("input/twitter-feed.json");
// parse JSON
JSONArray jsonArray = new JSONArray(string);
// use
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
System.out.println(jsonObject.getString("id"));
System.out.println(jsonObject.getString("text"));
System.out.println(jsonObject.getString("created_at"));
}
Thanks,
PD.

You need to read the file first, convert it to String then feed it to the JSONArray (I am assuming that you are using the JSON-Java Project. The code below illustrates how to read the file and set it to JSONArray
// read the source file, source comes from streaming API delimited by newline
// done by curl https://stream.twitter.com/1/statuses/sample.json?delimited=newline -utwitterUsername:twitterPasswd
// > /Projects/StackOverflow/src/so7655570/twitter.json
FileReader f = new FileReader("/Projects/StackOverflow/src/so7655570/twitter.json");
BufferedReader br = new BufferedReader(f);
ArrayList jsonObjectArray = new ArrayList();
String currentJSONString = "";
// read the file, since I ask for newline separation, it's easier for BufferedReader
// to separate each String
while( (currentJSONString = br.readLine()) != null ) {
// create new JSONObject
JSONObject currentObject = new JSONObject(currentJSONString);
// there are more than one way to do this, right now what I am doing is adding
// each JSONObject to an ArrayList
jsonObjectArray.add(currentObject);
}
for (int i = 0; i < jsonObjectArray.size(); i++) {
JSONObject jsonObject = jsonObjectArray.get(i);
// check if it has valid ID as delete won't have one
// sample of JSON for delete :
// {"delete":{"status":{"user_id_str":"50269460","id_str":"121202089660661760","id":121202089660661760,"user_id":50269460}}}
if(jsonObject.has("id")) {
System.out.println(jsonObject.getInt("id"));
System.out.println(jsonObject.getString("text"));
System.out.println(jsonObject.getString("created_at") + "\n");
}
}
Steps explanation :
Stream API does not provide valid JSON as a whole but rather a valid one specified by the delimited field. Which is why, you can't just parse the entire result as is.
In order to parse the JSON, I use the delimited to use newline since BufferedReader has a method readLine that we could directly use to get each JSONObject
Once I get each valid JSON from each line, I create JSONObject and add it to the ArrayList
I then iterate each JSONObject in the ArrayList and print out the result. Note that if you want to use the result immediately and don't have the need to use it later, you can do the processing itself in while loop without storing them in the ArrayList which change the code to:
// read the source file, source comes from streaming API
// done by curl https://stream.twitter.com/1/statuses/sample.json?delimited=newline -utwitterUsername:twitterPasswd
// > /Projects/StackOverflow/src/so7655570/twitter.json
FileReader f = new FileReader("/Projects/StackOverflow/src/so7655570/twitter.json");
BufferedReader br = new BufferedReader(f);
String currentJSONString = "";
// read the file, since I ask for newline separation, it's easier for BufferedReader
// to separate each String
while( (currentJSONString = br.readLine()) != null ) {
// create new JSONObject
JSONObject currentObject = new JSONObject(currentJSONString);
// check if it has valid ID as delete status won't have one
if(currentObject.has("id")) {
System.out.println(currentObject.getInt("id"));
System.out.println(currentObject.getString("text"));
System.out.println(currentObject.getString("created_at") + "\n");
}
}

You may try Gson:
For just arrays you can use:
Gson gson = new Gson();
//(Deserialization)
int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class);
To deserialize an array of objects, you can just do:
Container container = new Gson().fromJson(json, Container.class);
As shown here

Use ObjectMapper Class from jackson library like this :
//JSON from file to Object
Staff obj = mapper.readValue(new File("c:\\file.json"), Staff.class);
//JSON from URL to Object
Staff obj = mapper.readValue(new URL("http://mkyong.com/api/staff.json"), Staff.class);
//JSON from String to Object
Staff obj = mapper.readValue(jsonInString, Staff.class);

Related

Parse Json inside servlet

I have this array list in java
[ {"pname":"7", "qty":"222"},
{"pname":"8", "qty":"5"},
{"pname":"9", "qty":"60"} ]
I can access the first index which is object, how can I access the first element inside the first object which is "pname" key in java syntax. Please give me sample codes. Thanks.
I tried:
mylist.get(0)
but it only gives me the first object. I don't know how to access the first index inside the object.
here is my whole code from getting the data to parse it into json array and convert to array list
String data = request.getParameter("data");
JSONArray jsonArray = new JSONArray(data);
ArrayList<String> mylist = new ArrayList<String>();
JSONArray this_is_jsonArray = (JSONArray)jsonArray;
if (jsonArray == null) {
System.out.println("json is empty");
}
else
{
int length = this_is_jsonArray.length();
for (int i=0;i<length;i++){
mylist.add(this_is_jsonArray.get(i).toString());
}
}
output.append(mylist);
Basically I'm trying to do a function similar output to this mylist[0].pname in javascript. the expected output all in all is to save those pnames and qtys to a variable for me to able to send each value to the database
In order to write a proper answer you need to be very clear about the input and output you have and you expect.
I don't understand why you want to create a parallel data structure instead of using the parsed JSON but from what I read in comments I think that you need to change the structure of your ArrayList content in order to obtain the result you want to achieve.
String data = "[ {\"pname\":\"7\", \"qty\":\"222\"}, {\"pname\":\"8\", \"qty\":\"5\"}, {\"pname\":\"9\", \"qty\":\"60\"} ]" ;
HashMap<String, String> item = new HashMap<String, String>();
JSONArray jsonArray = new JSONArray(data);
ArrayList<HashMap> mylist = new ArrayList<HashMap>();
if (jsonArray == null) {
System.out.println("json is empty");
} else {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
item.put("pname", jsonObject.getString("pname"));
item.put("qty", jsonObject.getString("qty"));
mylist.add(item);
}
}
System.out.println(mylist);
First thing to consider is JSON object is not ordered.The first object can be pname or qty, in successive request. To access the fields, give field name as an associative array.
JSONArray jsonArray = new JSONArray(data);
ArrayList<String> mylist = new ArrayList<String>();
JSONArray this_is_jsonArray = (JSONArray)jsonArray;
if (jsonArray == null) {
System.out.println("json is empty");
}
else
{
int length = this_is_jsonArray.length();
for (int i=0;i<length;i++){
// Just this line is modified
mylist.add(this_is_jsonArray.getJSONObject(i).getString("pname").toString());
}
}

Simple JSON unexpected token { at position > 1

I'm trying to use JSON simple as part of a Java application to pull specific data from a .json file. Whenever I run the program, I get an unexpected token error message when it tries to parse.
A simplified version of the JSON file is as follows:
{"id":123,"text":"sample1","user":{"id":111,"name":"username"},"lang":"en"}
{"id":345,"text":"sample2","user":{"id":555,"name":"user2"},"lang":"en"}
My code is as follows:
public static void readJSON() {
JSONParser jsonParser = new JSONParser();
try {
FileReader reader = new FileReader(fileLocation);
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
JSONArray jsonArray = (JSONArray) jsonObject.get("");
Iterator<?> i = jsonArray.iterator();
while (i.hasNext()) {
JSONObject obj = (JSONObject) i.next();
int tweetID = (int) obj.get("id");
String lang = (String) obj.get("lang");
}
} catch (Exception e) {
e.printStackTrace();
}
}
In this example, the line of code:
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
throws an error due to an unexpected token at the first left brace ({) of the second JSON object (i.e, at the brace before "id":345).
How could I go about resolving this issue?
And, as a follow up, how would one also pull the information for the username in this example?
Thanks for taking the time to read through this, and for any assistance provided!
That file is an invalid JSON file, it contains an entire object on each line.
What you'll need to do is read the file line by line, and then passing each line to the parser to create a new object.
If you fix your code, you can solve unexpected token error.
public static void readJSON() {
JSONParser jsonParser = new JSONParser();
try {
FileReader reader = new FileReader(fileLocation);
//You need to fix this part
JSONArray jsonArray = (JSONArray) jsonParser.parse(reader);
Iterator<?> i = jsonArray.iterator();
while (i.hasNext()) {
JSONObject obj = (JSONObject) i.next();
int tweetID = (int) obj.get("id");
String lang = (String) obj.get("lang");
}
} catch (Exception e) {
e.printStackTrace();
}
}
You are trying to parse JSON object, and you actually have two JSON objects.
And in your code you are actually expect an array of JSON objects.
So, use the proper JSON array:
[
{"id":123,"text":"sample1","user":{"id":111,"name":"username"},"lang":"en"},
{"id":345,"text":"sample2","user":{"id":555,"name":"user2"},"lang":"en"}
]
In order to quickly check your JSON syntax, you can use some online tool.
Your JSON is indeed wrong. It actually contains 2 valid JSONs. If you want to create one valid JSON document you have to wrap your input with { and } or [ ] if this is an array or collection. Please note the comma that separates 2 different entities.
[
{"id":123,"text":"sample1","user":{"id":111,"name":"username"},"lang":"en"},
{"id":345,"text":"sample2","user":{"id":555,"name":"user2"},"lang":"en"}
]

Parse JSON response into a List

I'm trying to parse a JSON response
it's structure is:
{
"metric": {
"name": "string",
"values": [
"string"
]
}
}
My code so far:
StringBuilder sb = new StringBuilder();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
sb.append(line);
}
wr.close();
reader.close();
JSONObject json = new JSONObject(sb.toString());
JSONArray jsonArray = json.getJSONArray("values");
List<String> list = new ArrayList<>();
String errorPercent ="";
for(int i = 0 ; i < json.length() ; i++){
errorPercent = jsonArray.getJSONArray(i).getString(i);
list.add(errorPercent);
}
The output I'm getting is saying that "values " was not found,
am I misunderstanding the structure of the JSON response?
Edit
It appears the structure I was given on the site I'm receiving the response from is not correct. it appears to be a more complicated structure
I have modified my code accordingly:
JSONObject json = new JSONObject(sb.toString());
JSONObject metricsData = json.getJSONObject("metric_data");
JSONArray metrics = metricsData.getJSONArray("metrics");
System.out.println(metrics.toString());
The print out is as follows:
[{"timeslices":[{"values":{"max_response_time":0,"calls_per_minute":0,"average_be_response_time":0,"error_percentage":0,"min_response_time":0,"requests_per_minute":0,"average_network_time":0,"average_response_time":0,"average_fe_response_time":0,"total_app_time":0,"call_count":0,"fe_time_percentage":0,"total_network_time":0,"total_fe_time":0,"network_time_percentage":0},"from":"2015-10-25T22:39:00+00:00","to":"2015-10-25T22:40:00+00:00"},{"values":{"max_response_time":0,"calls_per_minute":0,"average_be_response_time":0,"error_percentage":0,"min_response_time":0,"requests_per_minute":0,"average_network_time":0,"average_response_time":0,"average_fe_response_time":0,"total_app_time":0,"call_count":0,"fe_time_percentage":0,"total_network_time":0,"total_fe_time":0,"network_time_percentage":0},
There appears to be another array within the array: "timeslices" is that right? how do I get at that array?
I unsuccessfully tried:
JSONArray timeslices = metrics.getJSONArray("timeslices");
values is a field inside metric.
You'd need to first get the metric object, then look inside that for values.
JSONObject metric = json.getJSONObject("metric");
JSONArray jsonArray = metric.getJSONArray("values");

AutoSuggest in Android from jsonencoded array of php

I want to use json encoded array which i am return from this link :
http://sids.roundone.asia/suggest.json?data=soft
as suggestions in android application.
(I have used json_encode($arr) function in php file and i am returning that as response for above link)
I have a problem in reading this response in java and storing it in an ArrayList.
My code is :
try {
String temp=sName.replace(" ", "%20");
URL js = new URL("https://sids.roundone.asia/suggest.json?data="+temp);
URLConnection jc = js.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(jc.getInputStream()));
String line = reader.readLine();
JSONObject jsonResponse = new JSONObject(line);
JSONArray jsonArray = jsonResponse.getJSONArray("results");
for(int i = 0; i < jsonResponse.length(); i++){
JSONObject r = jsonArray.getJSONObject(i);
ListData.add(new SuggestGetSet(jsonResponse.get(String.vlaueOf(iss)));
}
}
As I could see on your link, you're returning a JSON Array, instead of a JSON Object, ( "[ ]" instead of "{ }") and then in your java code you're trying to create a JSONObject here:
JSONObject jsonResponse = new JSONObject(line);
Try changing that to:
JSONArray jsonResponse = new JSONArray(line);
You return JSON array directly not a JSON Object have inner array so cast your incoming response to JSONArray directly.
JSONArray jsonResponse = new JSONArray(line);

How to extract multiple JSON Objects into String

I am reading multiple JSONObject from a file and converting into a string using StringBuilder.
These are the JSON Objects.
{"Lng":"-1.5908601","Lat":"53.7987816"}
{"Lng":"-2.5608601","Lat":"54.7987816"}
{"Lng":"-3.5608601","Lat":"55.7987816"}
{"Lng":"-4.5608601","Lat":"56.7987816"}
{"Lng":"-5.560837","Lat":"57.7987816"}
{"Lng":"-6.5608294","Lat":"58.7987772"}
{"Lng":"-7.5608506","Lat":"59.7987823"}
How to convert into a string?
Actual code is:-
BufferedReader reader = new BufferedReader(new InputStreamReader(contents.getInputStream()));
StringBuilder builder = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
builder.append(line);
}
}
catch(IOException e)
{
msg.Log(e.toString());
}
String contentsAsString = builder.toString();
//msg.Log(contentsAsString);
I tried this code
JSONObject json = new JSONObject(contentsAsString);
Iterator<String> iter = json.keys();
while(iter.hasNext())
{
String key = iter.next();
try{
Object value = json.get(key);
msg.Log("Value :- "+ value);
}catch(JSONException e)
{
//error
}
}
It just gives first object. How to loop them?
try this and see how it works for you,
BufferedReader in
= new BufferedReader(new FileReader("foo.in"));
ArrayList<JSONObject> contentsAsJsonObjects = new ArrayList<JSONObject>();
while(true)
{
String str = in.readLine();
if(str==null)break;
contentsAsJsonObjects.add(new JSONObject(str));
}
for(int i=0; i<contentsAsJsonObjects.size(); i++)
{
JSONObject json = contentsAsJsonObjects.get(i);
String lat = json.getString("Lat");
String lng = json.getString("Lng");
Log.i("TAG", lat + lng)
}
What you do is you are loading multiple JSON objects into one JSON object. This does not make sense -- it is logical that only the first object is parsed, the parser does not expect anything after the first }. Since you want to loop over the loaded objects, you should load those into a JSON array.
If you can edit the input file, convert it to the array by adding braces and commas
[
{},
{}
]
If you cannot, append the braces to the beginning of the StringBuilder and append comma to each loaded line. Consider additional condition to eliminate exceptions caused by inpropper input file.
Finally you can create JSON array from string and loop over it with this code
JSONArray array = new JSONArray(contentsAsString);
for (int i = 0; i < array.length(); ++i) {
JSONObject object = array.getJSONObject(i);
}

Categories

Resources