How to read JSON in Java? - java

I have a JSON String and I got the data element's data to JSONObject. After I read this that resultant string is as follows. I'm using org.json library.
String dataStr = "[{\"name\":\"jhonny\",\"counts\":[\"50\",\"44\",\"46\"],\"url\":\"google\"},
{\"name\":\"john\",\"counts\":[\"344\",\"4\",\"18\"],\"url\":\"yahoo\"}]";
I tried to read the each element like following,
String dataStr = report.get("data").toString();
JSONObject data = new JSONObject(dataStr.substring(1));
System.out.println(data);
But my output is,
{"name":"jhonny","counts":["50","44","46"],"url":"google"}
The output contains only one element. How can I fix this?

JSONArray jsonarray = new JSONArray(datastr);
for(int i=0; i<jsonarray.length(); i++){
JSONObject data= jsonarray.getJSONObject(i);
System.out.println(data);
}

Using the org.json library:
JSONObject obj = new JSONObject("{interests : [{interestKey:Dogs}, {interestKey:Cats}]}");
List<String> list = new ArrayList<String>();
JSONArray array = obj.getJSONArray("interests");
for(int i = 0 ; i < array.length() ; i++){
list.add(array.getJSONObject(i).getString("interestKey"));
}

The problem is you are trying to read JSONArray as JSONObject.
To parse JSONArray you need to do something like: (Not sure which library you are using)
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
// jsonobject holds the desired element.
}

If you analyze your json string, you will notice that your json string contains multiple json object without outer object like :-
{
"outer":{
{\"name\":\"jhonny\",\"counts\":[\"50\",\"44\",\"46\"],\"url\":\"google\"},
{\"name\":\"jhonny\",\"counts\":[\"50\",\"44\",\"46\"],\"url\":\"google\"}
}
}
The way you are parsing require this kind of json structure. Your json string is actually just a jsonarray. So do like this way :
JSONArray jsonarray = new JSONArray(datastr);
for(int i=0; i<jsonarray.length(); i++){
JSONObject data= jsonarray.getJSONObject(i);
}
For more you can visit this link that gives you good explanation to how to read json in java

Related

Convert String to JSON Array from Web Request

i wanted to know how I can convert this string here to an array:
[{"title":"test","birth":"20.05"},{"title":"test","birth":"13.05"},{"title":"test","birth":"13.06"},{"title":"test","birth":"23.06"},{"title":"test","birth":"01.12"},{"title":"test","birth":"01.06"}]
I already found this here:
JSONObject jsnobject = new JSONObject(readlocationFeed);
JSONArray jsonArray = jsnobject.getJSONArray("locations");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
But if I try to make the object I always get null. And here:
JSONArray jsonArray = jsnobject.getJSONArray("locations");
I don't know what I should enter as "locations". Should I enter "[]" ?
Thanks really much for help!
Daniel
I don't know what I should enter as "locations". Should I enter "[]" ?
Nothing readlocationFeed is already a JSONArray. You just need
JSONArray jsonArray = new JSONArray(readlocationFeed);
without
JSONObject jsnobject = new JSONObject(readlocationFeed);
JSONArray jsonArray = jsnobject.getJSONArray("locations");
Shouldn't it be the other way around?
JSONArray jsnArray = new JSONArray(readlocationFeed);
Anyway I suggest you should use GSON for this kind of problem:
Gson gson = new Gson();
MyClass[] arr = gson.fromJson(str, MyClass[].class);
class MyClass{
double birth;
String title;
}

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.

How to write a JSONObject to a file, which has JSONArray inside it, in Java?

I have JSON file, that I need to read, edit and write out again.
Reading works fine, I struggle with the write part of the JSON Array in my data.
I use JSON.simple library to work with JSON in Java.
The file looks like this:
{
"maxUsers":100,
"maxTextLength":2000,
"maxFileSize":2000,
"services":
[
{
"serviceName":"Яндекc",
"className":"YandexConnector.class",
"isEnabled":true
},
{
"serviceName":"Google",
"className":"GoogleConnector.class",
"isEnabled":false
}
]
}
When I try to write JSON-data (variable obj) to file, the services array is broken. My writing code:
JSONObject obj = new JSONObject();
obj.put("maxUsers", this.getMaxUsers());
obj.put("maxTextLength", this.getMaxTextLength());
obj.put("maxFileSize", this.getMaxFileSize());
JSONArray servicesJSON = new JSONArray();
ArrayList<Service> servicesArray = this.getServices();
for(int i=0; i< servicesArray.size(); i++)
{
servicesJSON.add(servicesArray.get(i));
}
obj.put("services", servicesJSON);
FileWriter file = new FileWriter(filename);
obj.writeJSONString(file);
file.flush();
file.close();
This outputs:
{
"services":
[
translator.settings.Service#121c5df,
translator.settings.Service#45f4ae
],
"maxTextLength":2000,
"maxUsers":100,
"maxFileSize":2000
}
How can I write the JSON data correctly to a file, if I have it in a JSONArray like services ?
The code, where I read the JSON data from the file (that works fine):
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader(filename));
JSONObject jsonObject = (JSONObject) obj;
setMaxUsers((Long) jsonObject.get("maxUsers"));
setMaxTextLength((Long) jsonObject.get("maxTextLength"));
setMaxFileSize((Long) jsonObject.get("maxFileSize"));
// get all list of services
JSONArray serv = (JSONArray) jsonObject.get("services");
for (int i = 0; i < serv.size(); i++) {
JSONObject service = (JSONObject) serv.get(i);
Service servec = new Service();
servec.setServiceName((String) service.get("serviceName"));
servec.setClassName((String) service.get("className"));
servec.setIsEnabled((Boolean) service.get("isEnabled"));
services.add(i, servec);
}
The editing part is not yet written, so I call the writing part directly after the reading.
Have a look at the examples of JSON-simple.
It says here that you need to put the Objects one by one into the Array, using only primitive and String values. You may use Collections like Map that by themselves only contain String or primitive values.
JSONArray list = new JSONArray();
list.add("foo");
list.add(new Integer(100));
list.add(new Double(1000.21));
list.add(new Boolean(true));
list.add(null);
StringWriter out = new StringWriter();
list.writeJSONString(out);
So, adding your Services is not allowed and won't work. You should add a toMap method in it where you convert it to a Map and fromMap to convert it back.
Like this (in Services.java):
public Map toMap() {
HashMap<String, String> serviceAsMap = new HashMap<>();
servicesAsMap.put("serviceName", serviceName);
servicesAsMap.put("className", this.class.getName() + ".class");
servicesAsMap.put("isEnabled", isEnabled);
// ... continue for all values
return servicesAsMap;
}
then you can use that Map to populate your JSONArray like this:
JSONArray servicesJSON = new JSONArray();
ArrayList<Service> servicesArray = this.getServices();
for(int i=0; i< servicesArray.size(); i++)
{
servicesJSON.add(servicesArray.get(i).toMap()); // use the toMap method here.
}
obj.put("services", servicesJSON);
Have a look at JSONArray Documentation.Here you will get list of methods available.This JSONArray is inherited from java.util.ArrayList,so we can use the methods available for ArrayList to JSONArray.
JSONArray userList = JSONFile.readJSONArray("users.json");
JSONArray newuserList = new JSONArray() ;
JSONObject jsonobject , newjsonObject;
for (int i = 0; i < userList.size(); i++) {
jsonobject = (JSONObject) userList.get(i);
String id = (String) jsonObject.get("id");
String pass = (String) jsonObject.get("password");
newuserList.add(jsonObject);
// Here we are putting json object into newuserList which is of JSONArray type
try{
FileWriter file = new FileWriter( "/users.json",false);
newuserList.writeJSONString(newuserList, file);
file.close();
}
catch(Exception e ){
e.getMessage();
}
Hope this will help !

Reading JSON on Android, No Output

This is my JSON data.
{"JSONDATA":[{"key":0,"value":"--Any--"},{"key":61,"value":"Accounting"},{"key":81,"value":"Aerospace & Defense"},{"key":72,"value":"Automotive"},{"key":83,"value":"Banking"},{"key":84,"value":"Biotech"},{"key":85,"value":"Construction"},{"key":86,"value":"Customer Service"},{"key":87,"value":"Education"},{"key":82,"value":"Energy"},{"key":70,"value":"Finance"},{"key":193,"value":"Government"},{"key":194,"value":"Healthcare"},{"key":71,"value":"Insurance"},{"key":73,"value":"Legal"},{"key":62,"value":"Management"},{"key":63,"value":"Manufacturing"},{"key":64,"value":"Marketing\/Advertising"},{"key":77,"value":"Media - Journalism"},{"key":74,"value":"Pharmaceutical"},{"key":75,"value":"Real Estate"},{"key":76,"value":"Research"},{"key":65,"value":"Restaurant"},{"key":66,"value":"Retail"},{"key":67,"value":"Sales"},{"key":78,"value":"Science"},{"key":68,"value":"Telecommunications"},{"key":79,"value":"Training"},{"key":69,"value":"Transportation"},{"key":80,"value":"Utilities"}]}
I want to decode it on my Android App, This is the code i have used., But i don't get anything on my output. No errors too.
JSONObject jObject= new JSONObject();
JSONArray menuObject = new JSONArray(jObject.getString("JSONDATA"));
String app;
for (int i = 0; i<menuObject.length(); i++) {
{
app=menuObject.getJSONObject(i).getString("value").toString();
a.append(app); // a is my TextView
}
First off, you're not initializing your jObject with anything.
//pass in string
JSONObject jObject= new JSONObject(jsonString);
JSONObjects need something to parse, otherwise (the way you have it now) they initialize with no data, which isn't very helpful.
Secondly, you're using getString when you really want an array:
JSONArray menuObject = jObject.getJSONArray("JSONDATA");
getString is designed to return a piece of string data from a JSON object. "JSONDATA" holds an array, so we need to choose the correct type to retrieve.
Thirdly, you have a redundant toString(), as getString already returns a String:
app=menuObject.getJSONObject(i).getString("value");
Its wrong:
JSONArray menuObject = new JSONArray(jObject.getString("JSONDATA"));
Try:
JSONObject jObject= new JSONObject(yourJSONString);
JSONArray menuObject = jObject.getJSONArray("JSONDATA");
Keep one thing in mind:
Create a JSON Object with JSON String you want to parse and then you can fetch String/JSON Object or JSON Array from the created JSON Object.
Store your json response in a String
String jsonResponse="YOUR JSON RESPONSE STRING";
//Pass the string as below
JSONObject jObject= new JSONObject(jsonResponse);
JSONArray menuObject = jObject.getJSONArray("JSONDATA"));
String app;
for (int i = 0; i<menuObject.length(); i++) {
{
app=menuObject.getJSONObject(i).getString("value").toString();
a.append(app); // a is my TextView
}
Use the appropiate getters and setters in JSONObject and JSONArray, and your "JSONDATA" entry is not a string. Do something like this:
JSONObject jObject = new JSONObject(yourJsonString);
JSONArray menuArray = jObject.getJSONArray("JSONDATA");
for (int i = 0; i < menuArray.length(); i++) {
String app = menuObject.getJSONObject(i).getString("value");
a.append(app); // a is my TextView
}
Use following code for parse your json string.
JSONObject obj = new JSONObject(youtString);
JSONArray array = obj.getJSONArray("JSONDATA");
for (int i = 0; i < array.length(); i++) {
JSONObject c = array.getJSONObject(i);
String key = c.getString("key");
String value = c.getString("value");
a.append(value);
}
Use this:-
String result="[{"key":0,"value":"--Any--"},{"key":61,"value":"Accounting"},{"key":81,"value":"Aerospace & Defense"},{"key":72,"value":"Automotive"},{"key":83,"value":"Banking"},{"key":84,"value":"Biotech"},{"key":85,"value":"Construction"},{"key":86,"value":"Customer Service"},{"key":87,"value":"Education"},{"key":82,"value":"Energy"},{"key":70,"value":"Finance"},{"key":193,"value":"Government"},{"key":194,"value":"Healthcare"},{"key":71,"value":"Insurance"},{"key":73,"value":"Legal"},{"key":62,"value":"Management"},{"key":63,"value":"Manufacturing"},{"key":64,"value":"Marketing\/Advertising"},{"key":77,"value":"Media - Journalism"},{"key":74,"value":"Pharmaceutical"},{"key":75,"value":"Real Estate"},{"key":76,"value":"Research"},{"key":65,"value":"Restaurant"},{"key":66,"value":"Retail"},{"key":67,"value":"Sales"},{"key":78,"value":"Science"},{"key":68,"value":"Telecommunications"},{"key":79,"value":"Training"},{"key":69,"value":"Transportation"},{"key":80,"value":"Utilities"}]";
JSONArray menuObject = new JSONArray(result);
String app;
for (int i = 0; i<menuObject.length(); i++) {
{
app=menuObject.getJSONObject(i).getString("value").toString();
a.append(app); // a is my TextView
}

Categories