I have this code where "Ocupacion" is object class that have another atribute objects. (since is a large class i don't post all the atributes of the class)
public String genHor(){
Collection<Ocupacion> ocupas = new ArrayList<>();
ocupas= H.makeOcupacion();
Gson gson = new Gson();
return gson.toJson(ocupas);
}
Then in another class where i recive the json String and i want to parse it. I do that:
public void assig(String json){
JsonObject obj = new JsonParser().parse(json).getAsJsonObject();
}
Then i get the java.lang.IllegalStateException: Not a JSON Object
String json is like that:
[{"sesionConcreta":{"grup":{"NumGr":10,"TamGr":200,"subgrupo":[{"NumSub":11,"TamSub":200}],"asignatura":"prop"},"sessio":{"HorasSes":2,"TipoSes":"TEORIA"}},"aula":{"NomAu":"a5105","Capacidad":200,"Tipo":"lab"},"diayHora":{"Dia":"L","Hora":8}}]
[{"sesionConcreta":{"grup":{"NumGr":10,"TamGr":200,"subgrupo":[{"NumSub":11,"TamSub":200}],"asignatura":"prop"},"sessio":{"HorasSes":2,"TipoSes":"TEORIA"}},"aula":{"NomAu":"a5105","Capacidad":200,"Tipo":"lab"},"diayHora":{"Dia":"L","Hora":8}}]
it is a json array not a json object because it is in [] not in {}:
JsonArray jsonArr = new JsonParser().parse(json).getAsJsonArray();
JsonObject obj = jsonArr.get(0).getAsJsonObject();
JsonObject sesionConcretaObj = obj.get("sesionConcreta").getAsJsonObject();
JsonObject groupObj = sesionConcretaObj.get("grup").getAsJsonObject();
int numGr = groupObj.get("NumGr").getAsInt();
The jsonString is actually a jsonArray not a jsonObject. Try with below:
String jsonStr = "[{\"sesionConcreta\":{\"grup\":{\"NumGr\":10,\"TamGr\":200,\"subgrupo\":[{\"NumSub\":11,\"TamSub\":200}],\"asignatura\":\"prop\"},\"sessio\":{\"HorasSes\":2,\"TipoSes\":\"TEORIA\"}},\"aula\":{\"NomAu\":\"a5105\",\"Capacidad\":200,\"Tipo\":\"lab\"},\"diayHora\":{\"Dia\":\"L\",\"Hora\":8}}]";
JSONArray jsonarray = new JSONArray(jsonStr);
for(int i = 0; i< jsonarray.length(); i++) {
JSONObject sesionConcreta = (JSONObject)jsonarray.getJSONObject(i).get("sesionConcreta");
JSONObject grup = (JSONObject)sesionConcreta.get("grup");
System.out.println(grup.get("NumGr"));
}
try this one:
public static void assig(String json){
Gson gson = new Gson();
Ocupacion[] occs = gson.fromJson(json, Ocupacion[].class);
System.out.println(occs);
}
Related
I'm trying to extract data from Github Sample Collection of Books but i am getting a blank screen. here is my JSON parsing code.
try {
JSONObject bookObject = new JSONObject(SAMPLE);
JSONArray booksArray = bookObject.getJSONArray("books");
for (int i = 0; i < booksArray.length(); i++){
JSONObject currentBook = booksArray.getJSONObject(i);
String title = currentBook.getString("title");
String author = currentBook.getString("author");
String isbn = currentBook.getString("isbn");
Book book = new Book(title,author,isbn);
books.add(book);
}
}catch (JSONException e){
Log.e("QueryUtils", "Problem parsing the earthquake JSON results", e);
}
I recommend to you use GSON, is very easy library
To Json
Gson gson = new Gson();
Staff obj = new Staff();
// 1. Java object to JSON file
gson.toJson(obj, new FileWriter("C:\\projects\\staff.json"));
// 2. Java object to JSON string
String jsonInString = gson.toJson(obj);
From Json
Gson gson = new Gson();
// 1. JSON file to Java object
Staff staff = gson.fromJson(new FileReader("C:\\projects\\staff.json"), Staff.class);
// 2. JSON string to Java object
String json = "{'name' : 'mkyong'}";
Staff staff = gson.fromJson(json, Staff.class);
// 3. JSON file to JsonElement, later String
JsonElement json = gson.fromJson(new FileReader("C:\\projects\\staff.json"), JsonElement.class);
String result = gson.toJson(json);
If you want to see more information about this you can check this link: https://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/
Try this :
Gson gson = new Gson();
JSONObject o = new JSONObject(jsonData.toString()); // pass your data here
JSONArray arr = new JSONArray(o.get("books").toString());
List<Book> books = new ArrayList<Book>();
for (int i = 0; i < arr.length(); i++) {
Book book = gson.fromJson(arr.get(i).toString(), Book.class);
books.add(book);
}
I have used Gson library here.
There are other libraries as well.
Refer this link for more details: http://tutorials.jenkov.com/java-json/gson-jsonparser.html
you need to convert the response from the network service to string and then get the jsonArray it will work
Like this ::
#Override
public void onResponse(Call call, final okhttp3.Response response) throws IOException {
final String stringResponse = response.body().string();
//insted of sample pass the stringresponse it will work
JSONObject bookObject = new JSONObject(stringResponse);
JSONArray booksArray = bookObject.getJSONArray("books");
for (int i = 0; i < booksArray.length(); i++){
JSONObject currentBook = booksArray.getJSONObject(i);
String title = currentBook.getString("title");
String author = currentBook.getString("author");
String isbn = currentBook.getString("isbn");
Book book = new Book(title,author,isbn);
books.add(book);
}
});
Check your model class , in that you set the parameters.
I have a json file formatted as the following:
[{
'title': 'Java',
'authors': ['Auth', 'Name']
},
{
'title': 'Java2',
'authors': ['Auth2', 'Name2']
},
{
'title': 'Java3',
'authors': ['Auth3', 'Name3']
}]
So i've tried using gson library to parse the file, with the following code:
JsonElement jelement = new JsonParser().parse(pathFile);
JsonObject jObject = jelement.getAsJsonObject();
JsonArray jOb = jObject.getAsJsonArray("");
final String[] jObTE = new String[jOb.size()];
for (int k=0; k<jObTE.length; k++) {
final JsonElement jCT = jOb.get(k);
JsonObject jOTE = jCT.getAsJsonObject();
JsonArray jContentTime = jOTE.getAsJsonArray("content_time");
final String[] contentTime = new String[jContentTime.size()];
for (int i=0; i<contentTime.length; i++) {
final JsonElement jsonCT = jContentTime.get(i);
JsonObject jObjectTE = jsonCT.getAsJsonObject();
JsonArray jTE = jObjectTE.getAsJsonArray("");
final String[] contentTimeTE = new String[jTE.size()];
for (int j=0; j<contentTimeTE.length; j++) {
final JsonElement jsonCTTE = jTE.get(j);
contentTime[j] = jsonCTTE.getAsString();
}
}
}
But, in doing so, i found this error: java.lang.IllegalStateException: Not a JSON Object at the second line.
You're trying to parse array to object, in which case you'll fail, because top level structure in your json is array.
I would parse this JSON in slightly different way
1) Create some Model class
public class Model {
private String title;
private List<String> authors;
//getters ...
}
2) Parse your JSON (
public static final String JSON_PATH = "/Users/dawid/Workspace/Test/test.json";
Gson gson = new Gson();
BufferedReader br = new BufferedReader(new FileReader(JSON_PATH));
Type type = new TypeToken<List<Model>>(){}.getType();
List<Model> models = gson.fromJson(br, type);
Your code is barely readable, so i guess that solved your problem
Second way:
BufferedReader br = new BufferedReader(new FileReader(JSON_PATH));
JsonParser parser = new JsonParser();
JsonArray array = parser.parse(br).getAsJsonArray();
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
}
I'm trying to parse below json file:
{"units":[{"id":42,
"title":"Hello World",
"position":1,
"v_id":9,
"sites":[[{"id":316,
"article":42,
"clip":133904
}],
{"length":5}]
}, ..]}
This is what I have tried:
Object obj = null;
JSONParser parser = new JSONParser();
Object unitsObj = parser.parse(new FileReader("file.json");
JSONObject unitsJson = (JSONObject) unitsObj;
JSONArray units = (JSONArray) unitsJson.get("units");
Iterator<String> unitsIterator = units.iterator();
while(unitsIterator.hasNext()){
Object uJson = unitsIterator.next();
JSONObject uj = (JSONObject) uJson;
obj = parser.parse(uj.get("sites").toString());
JSONArray jsonSites = (JSONArray) obj;
for(int i=0;i<jsonSites.size();i++){
JSONObject site = (JSONObject)jsonSites.get(i); // Exception happens here.
System.out.println(site.get("article");
}
}
The code is not working when I try to parse the inner json array, so I get:
Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject
The exception is pointing to this line:
JSONObject site = (JSONObject)jsonSites.get(i);
Any help? tnx.
I've found a working code:
JSONParser parser = new JSONParser();
Object obj = parser.parse(content);
JSONArray array = new JSONArray();
array.add(obj);
If you don't need the array (like the author), you can simply use
JSONParser parser = new JSONParser();
Object obj = parser.parse(content);
The first element of the sites array is an array, as you can see indenting the JSON:
{"units":[{"id":42,
...
"sites":
[
[
{
"id":316,
"article":42,
"clip":133904
}
],
{"length":5}
]
...
}
Therefore you need to treat its value accordingly; probably you could do something like:
JSONObject site = (JSONObject)(((JSONArray)jsonSites.get(i)).get(0));
this worked:
System.out.println("resultList.toString() " + resultList);
org.json.JSONObject obj = new JSONObject(resultList);
org.json.JSONArray jsonArray = obj.getJSONArray(someField);
for(int i=0;i<jsonArray.length();i++){
System.out.println("array is " + jsonArray.get(i));
}
JSONObject site=jsonSites.getJSONObject(i) should work out
JSONObject obj=(JSONObject)JSONValue.parse(content);
JSONArray arr=(JSONArray)obj.get("units");
System.out.println(arr.get(1)); //this will print {"id":42,...sities ..}
#cyberz is right but explain it reverse
You can first read the whole content of file into a String.
FileInputStream fileInputStream = null;
String data="";
StringBuffer stringBuffer = new StringBuffer("");
try{
fileInputStream=new FileInputStream(filename);
int i;
while((i=fileInputStream.read())!=-1)
{
stringBuffer.append((char)i);
}
data = stringBuffer.toString();
}
catch(Exception e){
LoggerUtil.printStackTrace(e);
}
finally{
if(fileInputStream!=null){
fileInputStream.close();
}
}
Now You will have the whole content into String ( data variable ).
JSONParser parser = new JSONParser();
org.json.simple.JSONArray jsonArray= (org.json.simple.JSONArray) parser.parse(data);
After that you can use jsonArray as you want.
If you want to re-filter the json data you can use following method. Given example is getting all document data from couchdb.
{
Gson gson = new Gson();
String resultJson = restTemplate.getForObject(url+"_all_docs?include_docs=true", String.class);
JSONObject object = (JSONObject) new JSONParser().parse(resultJson);
JSONArray rowdata = (JSONArray) object.get("rows");
List<Object>list=new ArrayList<Object>();
for(int i=0;i<rowdata.size();i++) {
JSONObject index = (JSONObject) rowdata.get(i);
JSONObject data = (JSONObject) index.get("doc");
list.add(data);
}
// convert your list to json
String devicelist = gson.toJson(list);
return devicelist;
}
JSONObject site = (JSONObject)jsonSites.get(i); // Exception happens here.
The return type of jsonSites.get(i) is JSONArray not JSONObject.
Because sites have two '[', two means there are two arrays here.
use your jsonsimpleobject direclty like below
JSONObject unitsObj = parser.parse(new FileReader("file.json");
JSONObject baseReq
LinkedHashMap insert = (LinkedHashMap) baseReq.get("insert");
LinkedHashMap delete = (LinkedHashMap) baseReq.get("delete");
I have a List<class> that I would like to convert into a json object and then traverse the data out of the json object.
If this were just a List<String> I could just do something like:
JSONObject obj = new JSONObject();
List<String> sList = new ArrayList<String>();
sList.add("val1");
sList.add("val2");
obj.put("list", sList);
Then I could traverse the list like:
JSONArray jArray = obj.getJSONArray("list");
for (int ii = 0; ii < jArray.size(); ii++)
System.out.println(jArray.getString(ii));
The problem with using the class is that I need to have access to data within each class element of my List<class> and I don't know how to encode that / traverse it into JSON. Any help would be greatly appreciated.
Call getJSONObject() instead of getString(). That will give you a handle on the JSON object in the array and then you can get the property off of the object from there.
For example, to get the property "value" from a List<SomeClass> where SomeClass has a String getValue() and setValue(String value):
JSONObject obj = new JSONObject();
List<SomeClass> sList = new ArrayList<SomeClass>();
SomeClass obj1 = new SomeClass();
obj1.setValue("val1");
sList.add(obj1);
SomeClass obj2 = new SomeClass();
obj2.setValue("val2");
sList.add(obj2);
obj.put("list", sList);
JSONArray jArray = obj.getJSONArray("list");
for(int ii=0; ii < jArray.length(); ii++)
System.out.println(jArray.getJSONObject(ii).getString("value"));
Let us assume that the class is Data with two objects name and dob which are both strings.
Initially, check if the list is empty. Then, add the objects from the list to a JSONArray
JSONArray allDataArray = new JSONArray();
List<Data> sList = new ArrayList<Data>();
//if List not empty
if (!sList.isEmpty()) {
//Loop index size()
for(int index = 0; index < sList.size(); index++) {
JSONObject eachData = new JSONObject();
try {
eachData.put("name", sList.get(index).getName());
eachData.put("dob", sList.get(index).getDob());
} catch (JSONException e) {
e.printStackTrace();
}
allDataArray.put(eachData);
}
} else {
//Do something when sList is empty
}
Finally, add the JSONArray to a JSONObject.
JSONObject root = new JSONObject();
try {
root.put("data", allDataArray);
} catch (JSONException e) {
e.printStackTrace();
}
You can further get this data as a String too.
String jsonString = root.toString();
This is how I do it using Google Gson. I am not sure, if there are a simpler way to do this (with or without an external library).
Type collectionType = new TypeToken<List<Class>>() {
}.getType();
String gsonString = new Gson().toJson(objList, collectionType);
You could use a JSON serializer/deserializer like flexjson to do the conversion for you.
Just to update this thread, here is how to add a list (as a json array) into JSONObject.
Plz substitute YourClass with your class name;
List<YourClass> list = new ArrayList<>();
JSONObject jsonObject = new JSONObject();
org.codehaus.jackson.map.ObjectMapper objectMapper = new
org.codehaus.jackson.map.ObjectMapper();
org.codehaus.jackson.JsonNode listNode = objectMapper.valueToTree(list);
org.json.JSONArray request = new org.json.JSONArray(listNode.toString());
jsonObject.put("list", request);