Parse JSON multiple objects - java

I am trying to parse the below json but unable to do that as stack over flow error comes in.
Here is the JSON -
[{
"Class": "1",
"school": "test",
"description": "test",
"student": [
"Student1",
"Student2"
],
"qualify": true,
"annualFee": 3.00
}]
Here is the code which is failing currently.
String res = cspResponse.prettyPrint();
org.json.JSONObject obj = new org.json.JSONObject(res);
org.json.JSONArray arr = obj.getJSONArray(arrayName);
String dataStatus=null;
for (int i = 0; i < arr.length(); i++) {
dataStatus = arr.getJSONObject(i).getString(key);
System.out.println("dataStatus is \t" + dataStatus);
}
Usecases are:
To get the value key "class"
Get the value from Student
Get the value from school
I appreciate your help.
update-1
Code more info on stack trace updated with below details.
cls = 1
error- org.json.JSONException: JSONObject["student "] not a string.
Stack trace-
public String getString(String key) throws JSONException {
Object object = this.get(key);
if (object instanceof String) {
return (String) object;
}
throw new JSONException("JSONObject[" + quote(key) + "] not a string.");
}
When I ran the code with the below answers, here its failing for student is not a string.
The answers I used from first two comments and both have the same error. I appropriate your help.

Your json fragment is invalid - the last comma breaks the parsing. But the rest of the code is quite workable.
String res = "[\n" +
" {\n" +
" \"Class\": \"1\",\n" +
" \"school\": \"test\",\n" +
" \"description\": \"test\",\n" +
" \"student\": [\n" +
" \"Student1\",\n" +
" \"Student2\"\n" +
" ],\n" +
" \"qualify\": true,\n" +
" \"annualFee\": 3.00\n" +
" }\n" +
"]";
JSONArray arr = new JSONArray(res);
for (int i = 0; i < arr.length(); i++) {
JSONObject block = arr.getJSONObject(i);
Integer cls = block.getInt("Class");
System.out.println("cls = " + cls);
Object school = block.getString("school");
System.out.println("school = " + school);
JSONArray students = block.getJSONArray("student");
System.out.println("student[0] = " + students.get(0));
System.out.println("student[1] = " + students.get(1));
}
should output
cls = 1
school = test
student[0] = Student1
student[1] = Student2

Your JSON reponse root is array but you consider your JSON response as JSON object
Changing your parsing json code as below
String res=cspResponse.prettyPrint();
org.json.JSONArray arr = new org.json.JSONArray(res);
String dataStatus=null;
for (int i = 0; i < arr.length(); i++) {
org.json.JSONObject obj=arr.getJSONObject(i);
dataStatus = obj.getString(key);
System.out.println("dataStatus is \t" + dataStatus);
String schoolName = org.getString("school");
System.out.println("school => " + schoolName);
org.json.JSONArray students = obj.getJSONArray("student");
System.out.println("student[0] = " + students.get(0));
System.out.println("student[1] = " + students.get(1));
}

You can use simple JSONObject class and Simple JSONParser for parsing the JSON.
1. Parse the JSON.
org.json.simple.JSONParser parser = new org.json.simple.JSONParser();
org.json.simple.JSONObject parsedJSON = parser.parse(inputJSON);
2. To get class:
String class = parsedJSON.get("Class");
3. To get Students:
org.json.simple.JSONArray studentArray = parsedJSON.get("student");
4. To Get School:
String school = parsedJSON.get("school");
After the above steps, you can run a for-loop to print the class and students.

Related

replace substring from string in java

I have the string hello Mr $name ur score is $value, What is the best way to get $name and $value part?
String json = "{\n" + "\"id\": 1,\n" + "\"data\":[\n" + "{\n"
+ "\"to\":123456789,\"name\":\"james\",\"value\":200\n" + "},\n" + "{\n"
+ "\"to\":123456789,\"name\":\"jhon\",\"value\":20\n" + "}]\n" + "}\n" + "";
Object obj = new JSONParser().parse(json);
JSONObject jsonObject = (JSONObject) obj;
long id = (long) jsonObject.get("id");
JSONArray arrayOfdata = (JSONArray) jsonObject.get("data");
JSONObject dataObject = new JSONObject();
ArrayList<String> data = new ArrayList<>();
for (String w : words) {
if (w.contains("$"))
if (json.contains(w.substring(1))) {
data.add(w.substring(1));
}
}
for (int n = 0; n < arrayOfdata.size(); n++) {
dataObject = (JSONObject) arrayOfdata.get(n);
for (int j = 0; j < data.size(); j++) {
String msg = message.replace(data.get(j).toString(), dataObject.get(data.get(j)).toString());
String strNew = msg.replace("$", "");
logger.info("strNew " + strNew);
}
}
Result
public static void main(String...strings) {
String inputString = "{\n" + "\"id\": 1,\n" + "\"data\":[\n" + "{\n" + "\"to\":123456789,\"name\":\"james\",\"value\":200\n" + "},\n" + "{\n" + "\"to\":123456789,\"name\":\"jhon\",\"value\":20\n" + "}]\n" + "}\n" + "";
Pattern pattern = Pattern.compile("(?:\"name\":\")(.*?)(?:\"value\":)[0-9]*");
Matcher m = pattern.matcher(inputString);
while (m.find()) {
String[] matches = m.group().split(",");
String name = null, value = null;
for (String match : matches) {
if(match.contains("name")){
name= match.substring(match.indexOf("name")+"name".length()).replaceAll("\"", "");
}else if(match.contains("value")) {
value= match.substring(match.indexOf("value")+"value".length()).replaceAll("\"", "");
}
}
System.out.println("Bonjour Mr. "+name+" votre score est value "+value);
}
}
I kind of understand the aim of your code, here is an attempt to get for each entry in the json array, the name and the values of each, I hope it helps.
String json = "{\n" + "\"id\": 1,\n" + "\"data\":[\n" + "{\n"
+ "\"to\":123456789,\"name\":\"james\",\"value\":200\n" + "},\n" + "{\n"
+ "\"to\":123456789,\"name\":\"jhon\",\"value\":20\n" + "}]\n" + "}\n" + "";
JSONObject jsonObject = new JSONObject(json);
JSONArray arrayOfdata = (JSONArray) jsonObject.get("data");
String message = "hello Mr %s your score is %s";
for (int i = 0; i < arrayOfdata.length(); i++) {
JSONObject obj = arrayOfdata.getJSONObject(i);
Object name = obj.get("name");
Object value = obj.get("value");
System.out.printf(message, name, value);
System.out.println();
}

Extracting data from JSON and modifying data

I want to extract jkl object from below JSON string. Also after extraction, I want the backslashes to be removed and extract further with the braces. I followed few questions on StackOverflow but it didn't help much.
{
"abc:def": {
"ghi": {
"jkl": "{\"mno:pqr\":{\"ty\":4,\"\\nsensing_service_name:\\\"Number\\\",\\nsensing_service_id: 20\\n}\\n ]\\n}\"}}",
"st": {
"op": 5,
"org": "q9wr9qrq"
},
"uvw": 1
},
"xyz": false
}
}
I tried below code to display jkl object but it is not working. Please suggest what is wrong in this and how to correct the same
JSONObject json = (JSONObject) JSONSerializer.toJSON(data);
JSONObject aa = json.getJSONObject("abc:def");
JSONObject bb = aa.getJSONObject("ghi");
JSONObject cc = bb.getJSONObject("jkl");
System.out.println(cc);
Hope this will help you:
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
public class TestClass {
public static void main(String[] args) throws Exception {
String jsonString = "{\n" +
" \"abc:def\": {\n" +
" \"ghi\": {\n" +
" \"jkl\": \"{\\\"mno:pqr\\\":{\\\"ty\\\":4,\\\"\\\\nsensing_service_name:\\\\\\\"Number\\\\\\\",\\\\nsensing_service_id: 20\\\\n}\\\\n ]\\\\n}\\\"}}\",\n" +
" \"st\": {\n" +
" \"op\": 5,\n" +
" \"org\": \"q9wr9qrq\"\n" +
" },\n" +
" \"uvw\": 1\n" +
" },\n" +
" \"xyz\": false\n" +
" }\n" +
"} ";
JSONObject jsonObject = new JSONObject(jsonString);
jsonObject = (JSONObject) jsonObject.get("abc:def");
jsonObject = (JSONObject) jsonObject.get("ghi");
String result = jsonObject.getString("jkl");
result = StringUtils.replace(result, "\\n", "");
System.out.println(result.replaceAll("\\\\",""));
}
}

check if there are two or more equal values in Json

How I should process this Json, to extract the cat1 value once in a Spinner, and in the second Spinner based on the first spinner selection I display book1 and book2.
Json:
{
"library":
[
{
"Cat": "cat1",
"Book": "book1",
"authur": "authur1"
},
{
"Cat": "cat1",
"Book": "book2",
"authur": "authur2"
},
{
"Cat": "cat2",
"Book": "book3",
"authur": "authur3"
}
]
}
You can simply use a library like Gson or Jackson for creating domain objects (you need to define them before) out of the Json. Afterwards you can easily extract whatever values you like.
This is an example:
http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/
Parse your JSON data and store it into ArrayList and populate it on Spinner using ArrayAdapter.
Here is a sample code for parsing your JSON data:
public void parseJson() {
String response = "{\n" +
" \"library\":\n" +
"[\n" +
"{\n" +
" \"Cat\": \"cat1\",\n" +
" \"Book\": \"book1\",\n" +
" \"authur\": \"authur1\"\n" +
" },\n" +
" {\n" +
" \"Cat\": \"cat1\",\n" +
" \"Book\": \"book2\",\n" +
" \"authur\": \"authur2\"\n" +
" },\n" +
" {\n" +
" \"Cat\": \"cat2\",\n" +
" \"Book\": \"book3\",\n" +
" \"authur\": \"authur3\"\n" +
" }\n" +
"]\n" +
"}";
try {
JSONObject mJsonObject = new JSONObject(response);
JSONArray libraryJsonArray = mJsonObject.getJSONArray("library");
ArrayList<String> cats = new ArrayList<>();
ArrayList<String> books = new ArrayList<>();
ArrayList<String> authors = new ArrayList<>();
// Get all jsonObject from jsonArray
for (int i = 0; i < libraryJsonArray.length(); i++)
{
JSONObject jsonObject = libraryJsonArray.getJSONObject(i);
// Cat
if (jsonObject.has("Cat") && !jsonObject.isNull("Cat")) {
cats.add(jsonObject.getString("Cat"));
}
// Book
if (jsonObject.has("Book") && !jsonObject.isNull("Book")) {
books.add(jsonObject.getString("Book"));
}
// Author
if (jsonObject.has("authur") && !jsonObject.isNull("authur")) {
authors.add(jsonObject.getString("authur"));
}
Log.d("SUCCESS", "JSON Object: " + "\nCat: " + cats.get(i)
+ "\nBook: " + books.get(i) + "\nAuthor: " + authors.get(i));
// Do something with ArrayList cats, books and authors
}
} catch (JSONException e) {
Log.e("FAILED", "Json parsing error: " + e.getMessage());
}
}
OUTPUT:
D/SUCCESS: JSON Object:
Cat: cat1
Book: book1
Author: authur1
D/SUCCESS: JSON Object:
Cat: cat1
Book: book2
Author: authur2
D/SUCCESS: JSON Object:
Cat: cat2
Book: book3
Author: authur3

How to replace a string inside of Json using java

[
"label": {
"originalName" : "Case #",
"modifiedLabel" : "Case #",
"labelId" : "case_number_lbl",
"isEditable" : "true",
"imageClass" : ""
}
]
In the above Json Array I need to replace "Case #" with "Ticket #". This is occuring in somany places. Any one update please.
Thanks In advance.
I think a simple loop should solve your problem:
public static void main(String[] args) throws JSONException {
JSONArray array = new JSONArray("[" +
" {" +
" originalName : \"Case #\"," +
" modifiedLabel : \"Case #\"," +
" labelId : \"case_number_lbl\"," +
" isEditable : \"true\"," +
" imageClass : \"\"" +
" }" +
"]");
System.out.println(array.toString(2));
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
JSONArray keys = object.names();
for (int j = 0; j < keys.length(); j++) {
String key = keys.getString(j);
if (object.getString(key).equals("Case #")) {
object.put(key, "Ticket #");
}
}
}
System.out.println();
System.out.println(array.toString(2));
}
You can use GSON to convert your json to java Object and then you can change your string .
You can exchange the value with the help String.replaceAll()
String jSONString = ...; // Your JSon string
String newString = jSONString.replace("Case #", "Ticket #");

Traverse JSON data in JAVA

I am new to JSON..Am using HTTPUrlConnections and getting some response in JAVA program.The response data will be like,
{
"data": [
{
"id": 1,
"userId": 1,
"name": "ABC",
"modified": "2014-12-04",
"created": "2014-12-04",
"items": [
{
"email": "abc#gmail.com",
"links": [
{
.
.
.
.
}
]
}
]
}
]
}
From this response am able to get the value of "name" field with the below java code.
JSONArray items = newObj.getJSONArray("data");
for (int it=0 ; it < items.length() ; it++){
JSONObject contactItem = items.getJSONObject(it);
String userName = contactItem.getString("name");
System.out.println("Name----------"+userName);
}
But my requirement is,I need to get the value of "email" ..How should I code for that..
Any advice..
Thanks in advance..
Chitra
You need to first get the items array and each entry of this array contains JSONObject, from which you can call getString("email") .E.g.
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class App
{
public static void main( String[] args ) throws JSONException {
JSONObject newObj = new JSONObject("{" +
"\"data\": [\n" +
" {\n" +
"\"id\": 1,\n" +
" \"userId\": 1,\n" +
" \"name\": \"ABC\",\n" +
" \"modified\": \"2014-12-04\",\n" +
" \"created\": \"2014-12-04\",\n" +
" \"items\": [\n" +
" {\n" +
" \"email\": \"abc#gmail.com\",\n" +
" \"links\": [\n" +
" {\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
"\n" +
"}");
JSONArray items = newObj.getJSONArray("data");
for (int it = 0; it < items.length(); it++) {
JSONObject contactItem = items.getJSONObject(it);
String userName = contactItem.getString("name");
JSONArray item = contactItem.getJSONArray("items");
for (int i = 0; i < items.length(); i++) {
String email = item.getJSONObject(i).getString("email");
System.out.println(email);
}
System.out.println("Name----------" + userName);
}
}
}
Output
abc#gmail.com
Name----------ABC
Extending your logic only:
JSONArray items = newObj.getJSONArray("data");
for (int it=0 ; it < items.length() ; it++){
JSONObject contactItem = items.getJSONObject(it);
String userName = contactItem.getString("name");
System.out.println("Name----------"+userName);
JSONArray itemsArr = contactItem.getJSONArray("items");
for (int item=0 ; item < itemsArr.length() ; item++){
String email = item.getString("email");
System.out.println("Email----------"+email);
}
}
This should work, with few tweaks. I have not actually tested it, just writing freehand here.
You can also use Jackson library from FasterXML. You can convert the JSON String into Java object very easily and then you can traverse using iterations on Collections.
If you look the JSON String it contains items which can be considered as an Array within an Array, so in order to get the value of email all you need to do is to create another JSONArray like:
JSONArray itemsArray = contactItem.getJSONArray("items");
Then you can retrieve the value of email over this Array
Thank you so much for your time and response.
The below code did the magic:
JSONArray responseContactData = responseContact.getJSONArray("data");
for (int i=0; i < responseContactData.length(); i++) {
String emails = contactDataValues.getJSONArray("items").getJSONObject(0).getString("email");
}

Categories