Parsing JSON array if I don't know array names - java

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("")
}

Related

How to parse this type of json using GSON?

Need to parse the JSON to Java Object, how to create a list using comma-separated string as an object example Intrest in the code below.
{
"following": [
],
"website": "",
"name": "Bala",
"gender": "",
"interest": [
"Cricket",
"FootBall",
"BasketBall"
],
"isConfirmed": true,
"posturl": [
"https://www.google.com",
"https://www.google.com"
],
"age": ""
}
interest in the json is not a comma separated String. It is an array. You can map it to List<String> type in java object.
Gson gson = new GsonBuilder().create();
JsonObject jsonObject = gson.fromJson(String YourJSONObject, JsonObject.class);
## Parsing JSON object ##
JsonArray interestarray = jsonObject.getAsJsonArray("interest");
## Storing JSONArray elements into Arraylist ##
List<String> list=new ArrayList<>();
for(JsonElement interest:interestarray){
list.add(interest.getAsString());
}

Return Java JsonPath as a json string

Using the java json path library: https://github.com/json-path/JsonPath
Given a json like this
{
"store": {
"book": [
{
"category": "reference"
},
{
"category": "fiction"
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
},
"expensive": 10
}
I would like to return "book" as a list of strings. For examples:
List<String> results = JsonPath.read(example, "$.store.book[*]");
And results should look like:
["{\"category\":\"reference\"}", "{\"category\":\"fiction\"}"]
Is there a way to achieve this?
Currently:
System.out.println(udf.jsonExtractScalar(testExample, "$.store.book[*]").getClass().getName());
--> net.minidev.json.JSONArray
As book is a JsonArray in you json tree, you can use JsonArray type and retrieve the data from it and add to the list.
Here is an example.
JSONArray jsonArray = new JSONArray(jsonArrayString);
List<String> list = new ArrayList<String>();
for (int i=0; i<jsonArray.length(); i++) {
list.add( jsonArray.getString(i) );
Replace jsonArrayString with you jsondata's books array name and you will be good to go.
The class used will be JSONArray class which is
`org.json.JSONArray`

how to create correct and specific json in a servlet in java

i need to return a json, example
"employees": [
{"firstName": "John", "lastName": "Doe"},
{"firstName": "Anna", "lastName": "Smith"},
{"firstName": "Peter", "lastName": "Jones"}
]
this is my code but i cant get the result
JSONArray array = new JSONArray();
ArrayList tipopropiedades = new ArrayList();
for (int i = 0; i < tp.length; i++) {
JSONObject detalle = new JSONObject();
TipoPropiedadTO ti = tp[i];
System.out.println(ti.getIdTipoCompra()+" "+ti.getNombreTipoCompra());
detalle.put("nombre",ti.getNombreTipoCompra().trim());
array.add(detalle);
}
the result of code when i get the alert(data) is
[{"nombre":"Casa"}, {"nombre":"Departamento"}, {"nombre":"Oficina"}, {"nombre":"Sitio Habitacional"}, {"nombre":"Sitio Comercial"}, {"nombre":"Sitio Industrial"}, {"nombre":"Agricola"}, {"nombre":"Parcela"}, {"nombre":"Bodega"}, {"nombre":"Estacionamiento"}]
What you need to return is a JSONObject containing that JSONArray as a field called "employees".
And you need to translate the fields in the objects you put into that JSONArray to have the proper names.

get values of array within array json in java

I need to get the values of the array "q1" which in array "questions", the arrays is json, and i need the values in java android.
{
"questions": [
{
"q1": [
"what my name?",
"a",
"b",
"c",
"Mac"
],
"q2": [
"what my age?",
"1",
"34",
"80",
"3"
]
}
]
}
Here I am answering your question to solve your problem but My friend you need to study first about json parsing.
Suggestion :
You can find example of it here :
http://primalpappachan.com/android/2010/06/05/parsing-json-in-android/
Answer :
JSONObject jresonseobj = response.getjObj();
JSONObject jobj;
JSONArray jsonArray = new JSONArray(jresonseobj.getString("questions"));
for (int i = 0; i < jsonArray.length(); i++)
{
jobj = jsonArray.getJSONObject(i);
// parse inner json here.
}

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

Categories

Resources