how to read JSON from HTTP GET request? - java

I have created a java server which gets HTTP GET request url as
/Star/getDetails?sentMsg=data.requestorName:ABC,data.companyName:EFG,portfolios:
[{name:,placeholder:Portfolio 1,positions:[{ticker:T1234,weight:29.85},
{ticker:T2345,weight:70.15}],active:false}],analyticsDate:20140630}
I have to parse sentMsg parameter such as I am able to read each variable individually. For eg, i should be able to read data.requestorName, companyName. I am not able to find a way to do it.
request.getParameter("sentMsg") always return String.
Tried parsing it through json-simple
JSONParser jp = new JSONParser();
try {
Object obj = jp.parse(sentMsg);
JSONArray ja = (JSONArray)obj;
} catch (ParseException e) {
e.printStackTrace();
}
But this gives parse exception. I have limitation to use json-simple jar only. Any suggestion on how to do it?

Get the paramter sentMsg from HttpRequest object store it into a string. Split from comma i.e. "," and the last second token would be the json string. You can now parse it using Json simple lib and extract values from it.

Provided you have valid JSON like:
private static String jsonString = "[{name : \"stackOverFlow\"}]";
Convert it to JSONArray like:
JSONArray jsonArray = new JSONArray(jsonString );
Then you can get value out of JSONArray by looping through it:
for (int i = 0; i < jsonArray.length(); i++) { //Iterating over mediaArray
JSONObject media = jsonArray.getJSONObject(i);
String nameFromJSON = media.getString("name");
System.out.println("Name = " + nameFromJSON);
}
Output will be:
//Name = stackOverFlow

Related

How to get values from JSONObject in Java?

I am trying to parse a JsonArray and get its values but I am gettign error when I use
jitem.getString("firstitem");
or
jitem.getJSONObject("firstitem");
or
jitem.get("firstitem");
Following is the code snippet.
JSONArray arr_items = new JSONArray(str);
if(arr_items!=null && arr_items.size()>0){
for(int i=0;i<arr_items.size();i++){
JSONObject jitem = arr_items.getJSONObject(i);//works fine till here
jitem.getString("firstitem"); //throws exception here
}
This is the JSONArray that I am parsing
[{"firstitem":"dgfd","secondtitem":"dfgfdgfdg","thirditem":"fdgfdgdf#sjhasjkdsha.com","fourthitem":"jkksdjklsfjskj"}]
what I am doing wrong? How to get these values by using keys?
Update:Note This array and its parameters are not null at all. They all have valid values.
First check arr_items is not empty.
Then, try surrounding your snippet with try/catch :
try {
your snippet
} catch (JSONException e) {
e.printStackTrace();
}
Check below
String json ="{'array':" + "[{'firstitem':'dgfd','secondtitem':'dfgfdgfdg','thirditem':'fdgfdgdf#sjhasjkdsha.com','fourthitem':'jkksdjklsfjskj'}]"+ "}";
JSONObject myjson = new JSONObject(json);
JSONArray the_json_array = myjson.getJSONArray("array");
int size = the_json_array.length();
// ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
for (int i = 0; i < size; i++) {
JSONObject another_json_object = the_json_array.getJSONObject(i);
// arrays.add(another_json_object);
System.out.println(another_json_object.get("firstitem"));
}
it require some array name so appended array name to it , if you want without it you have to add GSON.

How to Read Json array values from file

JSONArray jsonArray = (JSONArray) obj;
When I use the above code, it shows the error message:
java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray
Please anyone suggest any method to overcome this error or any other way to read json value form a file in Java (Desktop application).
Use this for get json value in string format from file
public String loadJSONFromFile() {
String json = null;
try {
InputStream is = getActivity().getAssets().open("yourfilename.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
JsonObject is a child of a JsonArray, so as per my suggestion use like this
final JSONArray jsonArray = new JSONArray();
jsonArray.put(obj); //obj is your JsonObject
and you can get JsonObject from array like
jsonArray.getJSONObject(0); //0 is index of your JsonObject in JsonArray
Hope this help you.
Check the content of the file.
It seems that the content is not an array, but a json object.
Open the file with a text editor. If the content is something like:
{ // First character
... content here
} // Last character
it is an object, if it is similar to
[ // First character
... content here
] // Last character
it is an array.
If you need to read an object you need to change your code as follow:
JSONObject jsonObject = (JSONObject) obj;
JSONArray jsonArray = (JSONArray) obj;
This obj is of JsonObject type, so change that line to
JSONObject jsonObject = (JSONObject)obj;

getString not working for JSON key

I'm learning how to work with JSON's in java and I'm having a problem using getString for one of my keys. My code is here:
public static void getJSON(String matchID){
String s = "";
String test = "{\"employees\":[{\"firstName\":\"John\", \"lastName\":\"Doe\"}]}";
try {
JSONObject hi = new JSONObject(test);
JSONArray stuff = hi.getJSONArray("employees");
String[] items = new String[stuff.length()];
items[0] = stuff.getString("firstName");
} catch (JSONException e) {
e.printStackTrace();
}
}
The "getString" is underlined in red, and the "The method getString(int) in the type JSONArray is not applicable for the arguments (String)" I was following an answer to another question word for word almost, and this happens, any advice? Thanks!
EDIT:
I need to get the specifics by name ie. "firstName" because I will be working with thousands of JSONs that each have hundreds of lines.
You need to get the JSOnObject first from the JSONArray(stuff) before you can call getString().
if you want to get the first element in the jsonarray and get its string this is how you would do it
JsonObject obj = stuff.getJsonObject(0);
String name = obj.getString("firstname");
So I figured out my problem, I didn't realize I had an JSONObject first, my apologies. Fixed like this:
JSONObject hi = new JSONObject(test);
JSONArray stuff = hi.getJSONArray("employees");
JSONObject name = stuff.getJSONObject(0);
String[] items = new String[hi.length()];
items[0]=name.getString("firstName");
System.out.println(items[0]);
you can try the simplest way to Parse in JSON
JSONParser parser=new JSONParser();
String s = "{\"employees\":[{\"firstName\":\"John\", \"lastName\":\"Doe\"}]}";
try{
Object obj = parser.parse(s);
JSONArray array = (JSONArray)obj;
System.out.println(array.get(1));
}catch(ParseException pe){
}

Java - looping through JSONArray

i am trying to call an URL and afterwards to save the results of the URL into a database.
The call of the URL is working and i also am able to save the result into JSON objects/arrays.
This is my code so far:
JSONParser parser = new JSONParser();
try
{
// responseString is the answer i get from calling the URL.
// It's pretty long that's why i don't copy it in here now
// But you can call this URL to see what the result is:
// http://www.gw2spidy.com/api/v0.9/json/items/all/1?filter_ids=29169,29185
Object objToParse = parser.parse(responseString);
JSONObject jsonObject = (JSONObject) objToParse;
JSONArray array = (JSONArray) jsonObject.get("results");
// Until here everything is ok, the results get saved into the array
JSONObject mJsonObject = new JSONObject();
for (int i = 0; i < array.length() ; i++)
{
mJsonObject = (JSONObject)array.get(i);
System.out.println(mJsonObject);
}
}
catch(ParseException pe)
{
System.out.println("position: " + pe.getPosition());
System.out.println(pe);
}
When i try to run this i get an error when i try to loop through the array:
Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to java.lang.CharSequence
I already searched for solutions but i cannot find or understand what is causing the error for me, would be nice if someone can help me here..
Ok at the end this was working for me:
JSONObject jsonObject = new JSONObject(responseString);
JSONArray array = (JSONArray) jsonObject.get("results");
JSONObject mJsonObject = new JSONObject();
for (int i = 0; i < array.length() ; i++)
{
mJsonObject = (JSONObject)array.get(i);
System.out.println(mJsonObject);
}
Had to change org.json.simple to instead use org.json and changed some lines then it was working.
I rather think that your implementation using simple json was wrong.
Although you didn't mention exactly, the only place your Exception could happen would be the line
JSONArray array = (JSONArray) jsonObject.get("results");
and as this is the same in both implementations, something previous to that must have happened leading to a situation with simple json where the results property is not a JSONArray. Probably something with parser.parse(...).

Convert returned JSON String to a JSONArray

I have a web service that performs a database query, converts the result set to a JSON String and returns the strung to the client. This is the code for the converter (I got it from http://biercoff.com/nice-and-simple-converter-of-java-resultset-into-jsonarray-or-xml/):
public static String convertToJSON(ResultSet resultSet)
throws Exception {
JSONArray jsonArray = new JSONArray();
while (resultSet.next()) {
int total_rows = resultSet.getMetaData().getColumnCount();
JSONObject obj = new JSONObject();
for (int i = 0; i < total_rows; i++) {
obj.put(resultSet.getMetaData().getColumnLabel(i + 1)
.toLowerCase(), resultSet.getObject(i + 1));
}
jsonArray.add(obj);
}
return jsonArray.toJSONString();
}
In the client application when I print the returned string it is in the following format:
[{"Column1":0.333333,"Column2":"FirmA"},{"Column1":0.666667,"Column2":"FirmB"}]
so far all is good. The problem I am having is converting the returned string into a JSON array. I tried this:
JSONArray arr = new JSONArray(JSON_STRING);
but got the following error message: constructor JSONArray in class JSONArray cannot be applied to given types. I tried to first convert in into a JSON object like so:
JSONObject obj = new JSONObject(JSON_STRING);
but got the following error: incompatible types: String cannot be converted to Map. What am I doing wrong? Thanks.
Apparently the problem was with the json library that I was using. Once I used the
import org.json.JSONArray;
it all worked out well. I was able to convert the returned string to an array using
JSONArray arr = new JSONArray(JSON_STRING);
and to iterate through the values I used the code provided in this answer: Accessing members of items in a JSONArray with Java which I reproduce here for simplicity:
for (int i = 0; i < arr.length(); ++i) {
JSONObject rec = arr.getJSONObject(i);
int id = rec.getInt("id");
String loc = rec.getString("loc");
// ...
}
well you need to do it by this way for example
String jsonText = "[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
try {
JSONArray array = new JSONArray(jsonText);
System.out.println(array);
System.out.println(array.length());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
Check the correct library used. The mess is that org.json.simple is often suggested by IDE as default for JSONObject and JSONArray.
You can find a link to latest jar for org.json library above.

Categories