remove outer quote from json array - java

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"
}]

Related

How to get a list from a JsonArray of objects

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.

Parsing JSON array if I don't know array names

I've got this JSON file. But what to do if I dont know array names (First, Second). How to parse this file in android?
Thanx
{
"First": [
"Test1",
"Test2",
"Test3",
"Test4",
"Test5"
],
"Second": [
"Test1",
"Test2"
] }
JSON you're working with already is an array. So, don't construct an instance of JSONObject; use a JSONArray. This should suffice:
JSONArray jsonArray = new JSONArray(result);
for(int i=0;i<jsonArray.length();i++){
JSONObject e = jsonArray.getJSONObject(i);
String ex = jsonArray.getString("")
}

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

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

How to parse JSON in java and what are the differences between JSONObect and JSONArray? [duplicate]

This question already has answers here:
Converting JSON data to Java object
(14 answers)
Closed 8 years ago.
{
"users":[ {
"user":"hi","password":"hi"
}, {
"user":"test","password":"test"
}
]
}
How to parse this type of JSON Objects?
Please help..
You need to use a json library like gson, jsonlib or jackson.
JSONObject: it is a hash object like Map where key value pairs are used
JSONArray: It is a collection of objects like List
JSONObject works like a map with key-value pairs. Eg. Code looks like below :
JSONObject obj=new JSONObject();
obj.put("name","Hello");
obj.put("nickname","Hi");
StringWriter out = new StringWriter();
obj.writeJSONString(out);
String jsonText = out.toString();
System.out.print(jsonText);
JSONArray works like a list , Eg, code below:
JSONArray list = new JSONArray();
list.add("Hello");
list.add(new Integer(100));
System.out.print(list);
You can differentiate the JSONArray & JSONObject as below:
JSONArray
A JSONArray is an ordered sequence of values. Its external text form is a string wrapped in square brackets with commas separating the values.
[ {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},
{"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"},
{"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"}
]
JSONObject
A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names.
{"bindings": [
{"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},
{"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"},
{"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"}
]
};
You can parse the JSONObject as below:
JSONObject JsonObject = new JSONObject(json);
JSONArray JsonArray_ = JsonObject .getJSONArray("users");
for (int i = 0; i < numberOfItems; i++) {
JSONObject record= JsonArray_photo.getJSONObject(i);
parsedObject.user = record.getString("user"); //its the same for all fields
parsedObject.password = record.getString("password");
map.add(parsedObject);
}

Categories

Resources