How to get a list from a JsonArray of objects - java

I would like to convert the response.getBody of above call to array.
I am trying to parse only the array "data" of json as list.
JSON:
{
"totalValue": 21,
"data": [
{
"id": 1,
"firstname": "Tom",
"lastname":"Pit"
},
{
"id": 2,
"firstname": "Jim",
"lastname":"Sol"
}
]
}
So after some tries i reach here:
JSONParser parser = new JSONParser();
Object obj = (Object) parser.parse(response.getBody());
JSONArray array = new JSONArray();
array.add(obj);
This array has size: 1 in the array there is a json object with 2 values first is long value of the total value (21) second is JsonArray with value : all the values and key "data" .
I would like to parse the JsonArray as list of object in java...but whatever to try get the error most of the times.....
Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column
Any help?

If you want to parse the "data" as list of object in java you can try with:
Map<?, ?> mapResponse = response.getBody();
List<?> data = (List<?>)mapResponse.get("data");
I hope this help you.

Related

remove outer quote from json array

I want to remove the outer quote from the JSON array. I am using the simple-JSON library for this.
My JSON array contains a string of variable name arrayData like this - `
{
"Name": "stack",
"xyz": "something"
}, {
"info": "nothing",
"set": "get"
}
This array is in variable arrayData and I passed this arrayData to JSONArray.
JSONArray jsonArray= new JSONArray();
jsonArray.add(arrayData);
JSONObject obj = new JSONObject();
obj .put("Info", jsonArray);
When I print this jsonArray. I am getting the result with double quote inside square bracket like this -
["{
"Name": "stack",
"xyz": "something"
}, {
"info": "nothing",
"set": "get"
}"]
This is the invalid JSON which I have tried on JSONlint.com
I want to remove the starting double quote inside the square bracket and end double quote. How can I solve this ?? Please suggest any solution for this.
You have to build the json object-by-object. putting it all in one String does not work:
JSONObject obj = new JSONObject();
obj.put("Name", "stack");
obj.put("xyz", "something");
JSONArray jsonArray= new JSONArray();
jsonArray.add(obj);
// same for 2nd item
I Tried:
JsonParser parser = new JsonParser();
JsonArray json = (JsonArray) parser.parse("[{\"Name\": \"stack\",\"xyz\": \"something\"}, {\"info\": \"nothing\",\"set\": \"get\"}]");
System.out.println(json.toString());
And the output is:
[{"Name":"stack","xyz":"something"},{"info":"nothing","set":"get"}]
Is that what you were looking for?
Your input JSON is not valid, and is not an Array. You need braces "[" at start and "]" end of JSON
[{
"Name": "stack",
"xyz": "something"
}, {
"info": "nothing",
"set": "get"
}]

Parsing nested json array in java

I have json file in below format.
{
"data":[
{
"prjId": 1,
"name" : "Forj1",
"issue": [
{
"id": 00001,
"status" : "Closed"
},
{
"id": 00002,
"status" : "Open"
}
]
},
{
"prjId": 2,
"name" : "Forj2",
"issue": [
{
"id": 00003,
"status" : "Closed"
},
{
"id": 00004,
"status" : "Open"
}
]
}],
"issueCounter": 7,
"success": true
}
Here "data" is array of projects, and within project attribute there is array of "issue".
So far if I remove "issue" array, I am able to traverse the json to one level down in "data" attribute, If this json has "issue" array I get an error saying missing comma.
javax.json.stream.JsonParsingException: Invalid token=NUMBER at (line no=15, column no=14, offset=242) Expected tokens are: [COMMA]
Below is the code that I have right now. I have two problems with this, one is the error while reading if I place the "issue" attribute, and secondly a way to read the "issue" array and traverse all attributes within.
InputStream fis = new FileInputStream(pathToFile+"data3.json");
JsonReader jsonReader = Json.createReader(fis);
//the error is thrown on below line while reading the above json.
JsonObject jsonObject = jsonReader.readObject();
jsonReader.close();
fis.close();
System.out.println(jsonObject.getInt("issueCounter"));
//reading arrays from json
JsonArray jsonArrayData = jsonObject.getJsonArray("data");
Project [] prj = new Project[jsonArrayData.size()];
int index = 0;
for(JsonValue value : jsonArrayData){
JSONObject jsonObj = new JSONObject(value.toString());
System.out.println(jsonObj.getString("name"));
System.out.println(jsonObj.getInt("prjId"));
//this is also the place where I am stuck, I know I need to construct an array out of it by obtaining issue attribute. Below is very very wrong.
/*
JsonArray jsonArrayIssue = jsonObj.getJsonArray("issue");
for(JsonValue issue : jsonArrayIssue){
JSONObject jsonIssueObj = new JSONObject(issue.toString());
System.out.println(jsonIssueObj.getString("status"));
System.out.println(jsonIssueObj.getInt("id"));
}
*/
}
Any help or pointers is deeply appreciated. I can tweak the json if its required ultimately I need to maintain an array of issues.
The problem as others said is the JSON.
"id": 00001 <-- this is a number, numbers cannot start with a leading zero as per JSON stadard.
If you control the JSON you should tweak it.
Alternatively ff you don't, you can use a less strict parser like org.json.simple https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple
The code will be the same as yours, just adjusted to org.json.simple
try { ...
JSONObject rootJSON = (JSONObject) new JSONParser().parse(jsonString);
JSONArray dataList = (JSONArray) rootJSON.get("data");
for(Object projectObj: dataList.toArray()){
JSONObject project = (JSONObject)projectObj;
JSONArray issueList = (JSONArray) project.get("issue");
for(Object issueObj: issueList.toArray()){
JSONObject issue = (JSONObject) issueObj;
//do something with the issue
}
}
} catch (ParseException e) {
//do smth
e.printStackTrace();
}
Your json data is invalid.You can check here.
http://jsonlint.com
...issue": [{ "id": 00001,
"status": ----------------------^
Your id must be string number,string,boolean.Send 1,2,3,.... as return values and check if it works.
Your code looks okay the problem is the JSON formatting. Specifically the following lines:
"id": 00001,
"id": 00002,
"id": 00003,
"id": 00004,
Basically if you want it in that format you will need to set them as strings by wrapping the values in quotations i.e. "id": "00001" or you can use a valid number i.e. "id": 1

Need some assistance trying to parse this JSON response from our backend server

Currently working on an android app and I need help on how I can go about extracting the subfields within the responses field of this json object:
Currently I am doing the following to extract some of the other fields:
JSONObject json = new JSONObject(response2);
int id = json.getInt("id");
String desc = json.getString("description");
JSONObject json2 = json.getJSONObject("owner");
String username = json2.getString("userName");
You need to create logic to parse the data. Every item from the JSON string is in the JSONObject you created with
JSONObject json = new JSONObject(response2);
You're on the right track with what you're doing. Just use the corresponding methods available in JSONObject and JSONArray classes to move through the object.
Start with the main object
{ // <-- this is your main object (AKA JSONObject json = new JSONObject(response2))
"id": 1, // to pull this id use json.getInt("id");
"title": "some text here", // to pull this title use json.getString("title");
...
"owner": { // Here's the logic part, owner is itself, a JSON object. so now you must extract it and parse through it.
// to pull the "owner" JSON object, use JSONObject ownerObject = json.getJSONObject("owner");
"userId": 1, // Now use the ownerObject to pull it's values. ownerObject.getInt("userId");
"userName": "TestingUser", // to pull this userName use ownerObject.getString("userName");
...
}
...
}
If it's an array, for example:
"someJSONArray": [{ "id": 1, "userName": "TestingUser1" }, { "id": 2, "userName": "TestingUser2" }]
then you would call:
JSONArray someJSONArray = getJSONArray("someJSONArray");
// Get each object from the array.
JSONObject object1 = someJSONArray.getJSONObject(0);
JSONObject object2 = someJSONArray.getJSONObject(1);
or if the array contains a string, for example:
"someKey": [ 23, 435, 123, 6345, 123 ]
then you would call:
JSONArray someKeyArray = getJSONArray("someKey");
for (int i = 0; i < someKeyArray.length(); i++) {
// Extract the value.
int itemValue = someKeyArray.getInt(i);
}
The data is there, you just have to parse it.

parse JSON to grab 'name' from an array

I'm trying to grab the 'name' from the JSON snippet I've included. I have tried the following but what I'm expecting is never grabbed.
Edit: 'output' is the full JSON string in case it wasn't already understood ;)
JSONObject result = null;
JSONArray data = null;
try {
try {result = new JSONObject(output);} catch (JSONException e) {e.printStackTrace();}
try {
data = result.getJSONArray("data");
for(int a=0;a<data.length();a++){
System.out.println(result.getJSONObject(String.valueOf(a)).getString("name"));//getJSONObject("results")
}
Here is the JSON snippet I'm trying to work with:
{
"code": 200,
"status": "Ok",
"copyright": "© 2015 MARVEL",
"attributionText": "Data provided by Marvel. © 2015 MARVEL",
"attributionHTML": "Data provided by Marvel. © 2015 MARVEL",
"etag": "b130a8b7af591e4e7ca078753f9c5c8a76e55e5d",
"data": {
"offset": 0,
"limit": 20,
"total": 1485,
"count": 20,
"results": [
{
"id": 1011334,
"name": "3-D Man",
"description": "",
"modified": "2014
.
.
.
.
.
.
.
.
.
.
To get you started, "data" points to a JSON Object, not array. So it should be:
data = result.getJSONObject("data");
Then, "results" points to a JSON array:
JSONArray results = data.getJSONArray("results");
Then you can try your loop. You shouldn't be turning a into a String - getJSONObject() takes an int for the index.
In case you're confused between Objects and Arrays, a JSON object has key - value pairs and are enclosed in curly braces. The keys are strings and the values can be a mix of any type:
{"key1": 5, "key2": "value2", "key3": {
"anotherObject": [1,2,3,4]
}
}
An array is a list of objects and is enclosed in square brackets:
[{...}, {...}, {...}]
The elements in the list don't have to be JSON objects, and in good JSON they will all be of the same type:
[1,2,3,4,4] or ["we", "are", "in", "an", "array"]
JSONTokener jsonTokener = new JSONTokener(jsonVaule);
JSONObject jsonObject = (JSONObject) jsonTokener.nextValue();
Int code =jsonObject.getInt("code");
String status =jsonObject.getString("status");
//{obejcet,obejcet,...}
for data{} is the same way~
JSONObject dataJsObject = (JSONObject) jsonObject.getJsonObject("data");
int offset =dataJsObject.getInt(""iffset);
....
//[{},{}] this type is jsonArrary
JSONArray results = dataJsObject.getJSONArray("results");
for(JSONObject resultJsonObj:JSONArray){
Int id =jsonObject.getInt("id");
//...and so on
}
hope it can help you~
You can parse like that
JsonObject obj = new JsonObject(StringResponse);
String code = obj.getString(code);
//same way you can get other string
JsonObject obj1 = obj.getJsonObject(Data);
String offset= obj.getString(offset);
//same way you can get other string
JsonArray jsonarr = obj1.getJsonArray(results);
for(i=0;i< jsonarr.size(); i++){
JsonObject innerObj = jsorr.getJsonObject(i);
String id= obj.getString(id);
//same way you can get other string
}
Hope It will helpful for you

Extracting data from JSON array

I know its an array, but I am completely new to JSON and need help comprehending how this is structured, here is my attempt at extracting data:
String JSonString = readURL("//my URL is here");
JSONArray s = JSONArray.fromObject(JSonString);
JSONObject Data =(JSONObject)(s.getJSONObject(0));
System.out.println(Data.get("name"));
My JSON data that I have goes like this :
{
"sports": [
{
"name": "basketball",
"id": 40,
"uid": "s:40",
"leagues": [
{
"name": "National Basketball Assoc.",
"abbreviation": "nba",
"id": 46,
"uid": "s:40~l:46",
"groupId": 7,
"shortName": "NBA",
"athletes": []
}
]
}
],
"resultsOffset": 10,
"resultsLimit": 10,
"resultsCount": 1,
"timestamp": "2013-11-18T03:15:43Z",
"status": "success"
}
I dont really have a strong grasp of this stuff so all the help is appreciated.
Here is the idea :
JSONObject root = new JSONObject(yourJsonString);
JSONArray sportsArray = root.getJSONArray("sports");
// now get the first element:
JSONObject firstSport = sportsArray.getJSONObject(0);
// and details of the first element
String name = firstSport.getString("name"); // basketball
int id = firstSport.getInt("id"); // 40
JSONArray leaguesArray = firstSport.getJSONArray("leagues");
// and so on, you can process leaguesArray similarly
It should work (feel free to complain about compile errors if there are any)
Your JSON data is an object (it starts with a curly brace). In the next inner layer, there is a single array (at key "sports"):
String jsonString = readURL("//my URL is here");
JSONObject result = JSONObject(jsonString);
JSONArray sports = result.getJSONArray("sports");
JSONObject sport = sport.getJSONObject(0);
System.out.println(sport.getString("name"));
I might have used another JSON library than you.
JSON means JavaScript Object Notation.
Objects in javascripts are just containers and can be represented by key-value pairs. Please find below notations to understand about json.
Represent objects in json: E.g. Student
{"name" : "Robin", "rollnumber" : "1"}
Represent array in json : E.g. Array of students
[{"name" : "Robin", "rollnumber" : "1"}, {"name" : "Mark", "rollnumber" : "2"}]
You can understand more on JSON from diagrams on this link http://www.json.org/fatfree.html
There are various ways available to to convert JSON to javaobject and javaobject to JSON : One of them is http://wiki.fasterxml.com/JacksonInFiveMinutes
Adding detailed code here along with the imports .
If this helps.
import org.json.JSONException;
import org.json.JSONObject;
public class extractingJSON {
public static void main(String[] args) throws JSONException {
// TODO Auto-generated method stub
String jsonStr = "{\"name\":\"SK\",\"arr\":{\"a\":\"1\",\"b\":\"2\"},\"arrArray\":[{\"a\":\"1\",\"b\":\"2\"}]}";
JSONObject jsonObj = new JSONObject(jsonStr);
String name = jsonObj.getString("name");
System.out.println(name);
String first = jsonObj.getJSONObject("arr").getString("a");
System.out.println(first);
first = jsonObj.getJSONArray("arrArray").getJSONObject(0).getString("a");
System.out.println(first);
}
}

Categories

Resources