Related
String jsonResponse=Utils.getGsonInstance().toJson(Object);
jsonResponse returns :
[
{
"Key":"1",
"Code": "11",
},
{
"key":"2",
"code": "22",
}
]
End result I am looking for is to wrap this JSON-String in another Key E.g.
{
"MainObj":
[
{
"Key":"1",
"Code": "11",
},
{
"key":"2",
"code": "22",
}
]
}
Is there a way I can achieve this using GSON Api ?
I tried ::
JSONObject jsonObject = new JSONObject();
jsonObject.put("MainObj",jsonResponse);
Output I am getting is :
{"MainObj": "[{\"Key\":\"1",\"Code\":\"11\"}, {\"Key\":\"2",\"Code\":\"22\"}]"}
Continue with GSON like :
public class MainObj {
#SerializedName("MainObj")
public List<Key> Main;
public class Key {
#SerializedName("Key")
public String Key;
#SerializedName("code")
public String Code;
}
}
And change
JSONObject jsonObject = new JSONObject();
jsonObject.put("MainObj",jsonResponse);
by
String tmp = new Gson().toJson(new MainObj());
I am trying to parse a JSON String and map it to a hashmap, I have a valid JSONString from server but when I traverse through it, all I can get it is the first result.
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList = new ArrayList<HashMap<String,String>>();
JSONObject jsonObj = new JSONObject(value);
Log.d("Jello",jsonObj.toString());
peoples = jsonObj.getJSONArray("product");//check here
Log.d("Jello",peoples.toString());
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String service_group = c.getString("sgroup");
String service = c.getString("service");
String value = c.getString("value");
String updated_at = c.getString("updated_at");
HashMap<String,String> persons = new HashMap<String,String>();
persons.put("service_group",service_group);
persons.put("service",service);
persons.put("value",value);
persons.put("updated_at",updated_at);
personList.add(persons);
}
My JSON String is :
{"product":[{"sgroup":"Dummy_BIG_ONE","service":"Dummy_UNDER_BIG_ONE","code":"128","value":"0","updated_at":"2015-12-04 21:21:00"}]}{"product":[{"sgroup":"Hello Monkey","service":"Do u work","code":"123","value":"0","updated_at":"2015-12-04 21:27:51"}]}{"product":[{"sgroup":"Checking from Android Device","service":"Monkey","code":"12345","value":"0","updated_at":"2015-12-04 22:55:39"}]}{"product":[{"sgroup":"Checking from Android Device","service":"Monkey","code":"12345","value":"0","updated_at":"2015-12-04 22:55:40"}]}{"product":[{"sgroup":"Checking from Android Device","service":"Monkey","code":"12345","value":"0","updated_at":"2015-12-04 22:55:42"}]}{"product":[{"sgroup":"Hello World","service":"Donkey","code":"24411","value":"0","updated_at":"2015-12-04 22:57:05"}]}{"product":[{"sgroup":"lkfnhjdiofho","service":"dfjdifj","code":"1101","value":"0","updated_at":"2015-12-05 01:15:49"}]}{"product":[{"sgroup":"Baal","service":"Saal","code":"1234","value":"21","updated_at":"2015-12-05 01:34:59"}]}{"product":[{"sgroup":"Inis","service":"Mona","code":"1234","value":"1001","updated_at":"2015-12-05 01:39:51"}]}{"product":[{"sgroup":"Medical Treatment Loan","service":"Number of referral slip","code":"128","value":"0","updated_at":"2015-12-05 01:50:42"}]}{"product":[{"sgroup":"Medical Treatment Loan","service":"Number of referral slip","code":"128","value":"0","updated_at":"2015-12-05 01:55:12"}]}{"product":[{"sgroup":"Medical Treatment Loan","service":"Number of referral slip","code":"128","value":"1000","updated_at":"2015-12-05 01:56:10"}]}
or HERE
here is how I am sending the JSON
while($row = mysql_fetch_assoc($output))
{
$product = array();
$product["sgroup"] = $row["service_group"];
$product["service"] = $row["service"];
$product["code"] = $row["code"];
$product["value"] = $row["amount"];
$product["updated_at"] = $row["updated_at"];
// user node
$response["product"] = array();
array_push($response["product"], $product);
// echoing JSON response
echo json_encode($response);
}
I want to add all the data's from the JSON in my ArrayList so that I can use it later.
Thank you for your help.
First, there are online tools available to determine if your JSON is valid.
Here is a general example of a better way to format your JSON data:
<?php
$bigArray = array();
for ($x = 0; $x <= 10; $x++) {
$product = array();
$product["sgroup"] = $x;
$product["service"] = $x;
$product["code"] = $x;
$product["value"] = $x;
$product["updated_at"] = $x;
array_push($bigArray, $product);
}
// echoing JSON response
echo json_encode($bigArray);
?>
Which gives this valid JSON response that is simple and easy to parse:
[
{
"sgroup":0,
"service":0,
"code":0,
"value":0,
"updated_at":0
},
{
"sgroup":1,
"service":1,
"code":1,
"value":1,
"updated_at":1
},
{
"sgroup":2,
"service":2,
"code":2,
"value":2,
"updated_at":2
},
{
"sgroup":3,
"service":3,
"code":3,
"value":3,
"updated_at":3
},
{
"sgroup":4,
"service":4,
"code":4,
"value":4,
"updated_at":4
},
{
"sgroup":5,
"service":5,
"code":5,
"value":5,
"updated_at":5
},
{
"sgroup":6,
"service":6,
"code":6,
"value":6,
"updated_at":6
},
{
"sgroup":7,
"service":7,
"code":7,
"value":7,
"updated_at":7
},
{
"sgroup":8,
"service":8,
"code":8,
"value":8,
"updated_at":8
},
{
"sgroup":9,
"service":9,
"code":9,
"value":9,
"updated_at":9
},
{
"sgroup":10,
"service":10,
"code":10,
"value":10,
"updated_at":10
}
]
As for the parsing, using a HashMap is not the best way. Create a list of Person POJO objects.
First define the Person class:
class Person {
public String group;
public String service;
public String value;
public String updated;
public Person(String g, String s, String v, String u) {
group = g;
service = s;
value = v;
updated = u;
}
}
Then, parsing is fairly simple:
List<Person> personList = new ArrayList<>();
JSONArray jsonArr;
try {
jsonArr = new JSONArray(response);
for(int i=0;i<jsonArr.length();i++){
JSONObject c = jsonArr.getJSONObject(i);
String service_group = c.getString("sgroup");
String service = c.getString("service");
String value = c.getString("value");
String updated_at = c.getString("updated_at");
Person p = new Person(service_group, service, value, updated_at);
personList.add(p);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You should put your products into json array:
[
{
"product": {
"sgroup": "lkfnhjdiofho",
"service": "dfjdifj",
"code": "1101",
"value": "0",
"updated_at": "2015-12-05 01:15:49"
}
},
{
"product": {
"sgroup": "Baal",
"service": "Saal",
"code": "1234",
"value": "21",
"updated_at": "2015-12-05 01:34:59"
}
},
{
"product": {
"sgroup": "Inis",
"service": "Mona",
"code": "1234",
"value": "1001",
"updated_at": "2015-12-05 01:39:51"
}
},
{
"product": {
"sgroup": "Medical Treatment Loan",
"service": "Number of referral slip",
"code": "128",
"value": "0",
"updated_at": "2015-12-05 01:50:42"
}
},
{
"product": {
"sgroup": "Medical Treatment Loan",
"service": "Number of referral slip",
"code": "128",
"value": "0",
"updated_at": "2015-12-05 01:55:12"
}
},
{
"product": {
"sgroup": "Medical Treatment Loan",
"service": "Number of referral slip",
"code": "128",
"value": "1000",
"updated_at": "2015-12-05 01:56:10"
}
}
]
And you have to change your parser little bit:
JSONArray jsonArray = new JSONArray(string);
for(int i=0;i<jsonArray.length();i++){
JSONObject c = jsonArray.getJSONObject(i).getJSONObject("product");
String service_group = c.getString("sgroup");
String service = c.getString("service");
String value = c.getString("value");
String updated_at = c.getString("updated_at");
HashMap<String,String> persons = new HashMap<String,String>();
persons.put("service_group",service_group);
persons.put("service",service);
persons.put("value",value);
persons.put("updated_at",updated_at);
personList.add(persons);
}
You don't need put your object into "product" attribute, but directly into array :
[
{
"sgroup": "lkfnhjdiofho",
"service": "dfjdifj",
"code": "1101",
"value": "0",
"updated_at": "2015-12-05 01:15:49"
},
{
"sgroup": "Baal",
"service": "Saal",
"code": "1234",
"value": "21",
"updated_at": "2015-12-05 01:34:59"
},
I'm trying to deserialize a JSON object (from JIRA REST API createMeta) with unknown keys.
{
"expand": "projects",
"projects": [
{
"self": "http://www.example.com/jira/rest/api/2/project/EX",
"id": "10000",
"key": "EX",
"name": "Example Project",
"avatarUrls": {
"24x24": "http://www.example.com/jira/secure/projectavatar?size=small&pid=10000&avatarId=10011",
"16x16": "http://www.example.com/jira/secure/projectavatar?size=xsmall&pid=10000&avatarId=10011",
"32x32": "http://www.example.com/jira/secure/projectavatar?size=medium&pid=10000&avatarId=10011",
"48x48": "http://www.example.com/jira/secure/projectavatar?pid=10000&avatarId=10011"
},
"issuetypes": [
{
"self": "http://www.example.com/jira/rest/api/2/issueType/1",
"id": "1",
"description": "An error in the code",
"iconUrl": "http://www.example.com/jira/images/icons/issuetypes/bug.png",
"name": "Bug",
"subtask": false,
"fields": {
"issuetype": {
"required": true,
"name": "Issue Type",
"hasDefaultValue": false,
"operations": [
"set"
]
}
}
}
]
}
]
}
My problem is: I don't know the keys into "fields" (in the example below "issuetype", "summary", "description", "customfield_12345").
"fields": {
"issuetype": { ... },
"summary": { ... },
"description": { ... },
"customfield_12345": { ... }
}
It would be awesome if I could deserialize it as an array with the key as "id" in my POJO so the above example will looke like the following:
class IssueType {
...
public List<Field> fields;
...
}
class Field {
public String id; // the key from the JSON object e.g. "issuetype"
public boolean required;
public String name;
...
}
Is there a way I can achieve this and wrap in my model? I hope my problem is somehow understandable :)
If you don't know the keys beforehand, you can't define the appropriate fields. The best you can do is use a Map<String,Object>.
If there are in fact a handful of types, for which you can identify a collection of fields, you could write a custom deserializer to inspect the fields and return an object of the appropriate type.
I know it's old question but I also had problem with this and there are results..
Meybe will help someone in future : )
My Response with unknow keys:
in Model Class
private JsonElement attributes;
"attributes": {
"16": [],
"24": {
"165": "50000 H",
"166": "900 lm",
"167": "b.neutr.",
"168": "SMD 3528",
"169": "G 13",
"170": "10 W",
"171": "230V AC / 50Hz"
}
},
So I also checked if jsonElement is jsonArray its empty.
If is jsonObject we have data.
ProductModel productModel = productModels.get(position);
TreeMap<String, String> attrsHashMap = new TreeMap<>();
if (productModel.getAttributes().isJsonObject())
{
for (Map.Entry<String,JsonElement> entry : productModel.getAttributes().getAsJsonObject().entrySet())
{
Log.e("KEYS", "KEYS: " + entry.getKey() + " is empty: " + entry.getValue().isJsonArray());
if (entry.getValue() != null && entry.getValue().isJsonObject())
{
for (Map.Entry<String, JsonElement> entry1 : entry.getValue().getAsJsonObject().entrySet())
{
Log.e("KEYS", "KEYS INSIDE: " + entry1.getKey() + " VALUE: " + entry1.getValue().getAsString());
// and there is my keys and values.. in your case You can get it in upper for loop..
}
}
}
There is a perfectly adequate JSON library for Java that will convert any valid JSON into Java POJOs. http://www.json.org/java/
I've got JSON file, which I want to parse.
The JSON file ("myfile") has format as follows:
{
"LanguageLevels": {
"1": "Początkujący",
"2": "ŚrednioZaawansowany",
"3": "Zaawansowany",
"4": "Ekspert"
}
}
I want to retrieve value (ŚrednioZaawansowany) of Key 2 from Language Levels.
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JsonSimpleExample {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("myfile");
JSONObject jsonObject = (JSONObject) obj;
JSONObject jsonChildObject = (JSONObject)jsonObject.get("LanguageLevels");
What to do next? How I can iterate over it?
Maybe you're not using the latest version of a JSON for Java Library.
json-simple has not been updated for a long time, while JSON-Java was updated 2 month ago.
JSON-Java can be found on GitHub, here is the link to its repo: https://github.com/douglascrockford/JSON-java
After switching the library, you can refer to my sample code down below:
public static void main(String[] args) {
String JSON = "{\"LanguageLevels\":{\"1\":\"Pocz\\u0105tkuj\\u0105cy\",\"2\":\"\\u015arednioZaawansowany\",\"3\":\"Zaawansowany\",\"4\":\"Ekspert\"}}\n";
JSONObject jsonObject = new JSONObject(JSON);
JSONObject getSth = jsonObject.getJSONObject("LanguageLevels");
Object level = getSth.get("2");
System.out.println(level);
}
And as JSON-Java open-sourced, you can read the code and its document, they will guide you through.
Hope that it helps.
You will have to iterate step by step into nested JSON.
for e.g a JSON received from Google geocoding api
{
"results" : [
{
"address_components" : [
{
"long_name" : "Bhopal",
"short_name" : "Bhopal",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Bhopal",
"short_name" : "Bhopal",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "Madhya Pradesh",
"short_name" : "MP",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "India",
"short_name" : "IN",
"types" : [ "country", "political" ]
}
],
"formatted_address" : "Bhopal, Madhya Pradesh, India",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 23.3326697,
"lng" : 77.5748062
},
"southwest" : {
"lat" : 23.0661497,
"lng" : 77.2369767
}
},
"location" : {
"lat" : 23.2599333,
"lng" : 77.412615
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 23.3326697,
"lng" : 77.5748062
},
"southwest" : {
"lat" : 23.0661497,
"lng" : 77.2369767
}
}
},
"place_id" : "ChIJvY_Wj49CfDkR-NRy1RZXFQI",
"types" : [ "locality", "political" ]
}
],
"status" : "OK"
}
I shall iterate in below given fashion
to "location" : {
"lat" : 23.2599333,
"lng" : 77.412615
//recieve JSON in json object
JSONObject json = new JSONObject(output.toString());
JSONArray result = json.getJSONArray("results");
JSONObject result1 = result.getJSONObject(0);
JSONObject geometry = result1.getJSONObject("geometry");
JSONObject locat = geometry.getJSONObject("location");
//"iterate onto level of location";
double lat = locat.getDouble("lat");
double lng = locat.getDouble("lng");
You can see that JSONObject extends a HashMap, so you can simply use it as a HashMap:
JSONObject jsonChildObject = (JSONObject)jsonObject.get("LanguageLevels");
for (Map.Entry in jsonChildOBject.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
JSONArray jsonChildArray = (JSONArray) jsonChildArray.get("LanguageLevels");
JSONObject secObject = (JSONObject) jsonChildArray.get(1);
I think this should work, but i do not have the possibility to test it at the moment..
To see all keys of Jsonobject use this
String JSON = "{\"LanguageLevels\":{\"1\":\"Pocz\\u0105tkuj\\u0105cy\",\"2\":\"\\u015arednioZaawansowany\",\"3\":\"Zaawansowany\",\"4\":\"Ekspert\"}}\n";
JSONObject obj = new JSONObject(JSON);
Iterator iterator = obj.keys();
String key = null;
while (iterator.hasNext()) {
key = (String) iterator.next();
System.out.pritnln(key);
}
Try this, you can parse nested JSON
public static String getJsonValue(String jsonReq, String key) {
JSONObject json = new JSONObject(jsonReq);
boolean exists = json.has(key);
Iterator<?> keys;
String nextKeys;
String val = "";
if (!exists) {
keys = json.keys();
while (keys.hasNext()) {
nextKeys = (String) keys.next();
try {
if (json.get(nextKeys) instanceof JSONObject) {
return getJsonValue(json.getJSONObject(nextKeys).toString(), key);
} else if (json.get(nextKeys) instanceof JSONArray) {
JSONArray jsonArray = json.getJSONArray(nextKeys);
int i = 0;
if (i < jsonArray.length()) do {
String jsonArrayString = jsonArray.get(i).toString();
JSONObject innerJson = new JSONObject(jsonArrayString);
return getJsonValue(innerJson.toString(),key);
} while (i < jsonArray.length());
}
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
val = json.get(key).toString();
}
return val;
}
Here is an example of retrieving nested JSON object.
Department and Product are model classes.
Department class holds department as a String and products as ArrayList of Product
Product class holds name as a String
depts and products are ArrayList of corresponding model classes
String jsonDataString = readJSONDataFromFile();
JSONArray jsonArray = new JSONArray(jsonDataString);
for (int i=0; i<jsonArray.length(); ++i) {
JSONObject departmentJSONObject = jsonArray.getJSONObject(i);
String deptName = departmentJSONObject.getString("department");
JSONArray productsJSONArray = departmentJSONObject.getJSONArray("products");
for (int j =0; j <productsJSONArray.length();j++){
JSONObject productJSONObject = productsJSONArray.getJSONObject(j);
String prodName = productJSONObject.getString("name");
Product product = new Product(prodName);
products.add(product);
}
Department department = new Department(deptName, products);
depts.add(department);
Here is my raw json file
[
{
"department": "Cold Drink",
"products": [
{
"name": "lemonade",
"img": "some_url"
},
{
"name": "Oj",
"img": "some_url"
}
]
},
{
"department": "CD2",
"products": [
{
"name": "lemonade2",
"img": "some_url2"
},
{
"name": "oj2",
"img": "some_url2"
}
]
},
{
"department": "CD3",
"products": [
{
"name": "lemonade3",
"img": "some_url3"
},
{
"name": "oj3",
"img": "some_url3"
}
]
}
]
Suppose I have a JSON array like this:
[
{
"id": "429d30a1-9364-4d9a-92e0-a17e00b3afba",
"children": [],
"parentid": "",
"name": "Expo Demo"
},
{
"id": "f80f1034-9110-4349-93d8-a17e00c9c317",
"children":
[
{
"id":"b60f2c1d-368b-42c4-b0b2-a1850073e1fe",
"children":[],
"parentid":"f80f1034-9110-4349-93d8-a17e00c9c317",
"name":"Tank"
}
],
"parentid": "",
"name": "Fishtank"
},
{
"id": "fc8b0697-9406-4bf0-b79c-a185007380b8",
"children": [
{
"id":"5ac52894-4cb6-46c2-a05a-a18500739193",
"children":[
{
"id": "facb264c-0577-4627-94a1-a1850073c270",
"children":[
{
"id":"720472b5-189e-47f1-97a5-a18500a1b7e9",
"children":[],
"parentid":"facb264c-0577-4627-94a1-a1850073c270",
"name":"ubSubSub"
}],
"parentid": "5ac52894-4cb6-46c2-a05a-a18500739193",
"name": "Sub-Sub1"
}],
"parentid":"fc8b0697-9406-4bf0-b79c-a185007380b8", "name":"Sub"
},
{
"id":"4d024610-a39b-49ce-8581-a18500739a75",
"children":[],
"parentid":"fc8b0697-9406-4bf0-b79c-a185007380b8",
"name":"Sub2"
}
],
"parentid": "",
"name": "Herman"
},
{
"id": "a5b140c9-9987-4e6d-a883-a18c00726883",
"children": [
{
"id":"fe103303-fd5e-4cd6-81a0-a18c00733737",
"children":[],
"parentid":"a5b140c9-9987-4e6d-a883-a18c00726883",
"name":"Contains Spaces"
}],
"parentid": "",
"name": "Kiosk"
}
]
No I want to find a certain object based on a id and once I have that, I need its children and all its childrends children
So lets say i want to find the element with an id if 4d024610-a39b-49ce-8581-a18500739a75
That should find the Element Sub2
And now it should produce all the child elements ids witch will be:
facb264c-0577-4627-94a1-a1850073c270
720472b5-189e-47f1-97a5-a18500a1b7e9
Let say I would do
findElementsChildren("4d024610-a39b-49ce-8581-a18500739a75")
So i guess its two parts, first find the "parent" element. Then find its childrends childrends children etc..
Any help would be much appreciated!
You can use recursion to solve the problem of unlimited nesting. With Gson, it would be something like the following code snippet (not tested). Other libraries will provide structures as JsonElement as well.
private JsonElement findElementsChildren(JsonElement element, String id) {
if(element.isJsonObject()) {
JsonObject jsonObject = element.getAsJsonObject();
if(id.equals(jsonObject.get("id").getAsString())) {
return jsonObject.get("children");
} else {
return findElementsChildren(element.get("children").getAsJsonArray(), id);
}
} else if(element.isJsonArray()) {
JsonArray jsonArray = element.getAsJsonArray();
for (JsonElement childElement : jsonArray) {
JsonElement result = findElementsChildren(childElement, id);
if(result != null) {
return result;
}
}
}
return null;
}
Based on Stefan Jansen's answer I made some changes and this is what I have now:
nestedChildren declared globaly, and before the children are searched reset to new ArrayList()
private void findAllChild(JSONArray array) throws JSONException {
for ( int i=0;i<array.length();i++ ) {
JSONObject json = array.getJSONObject(i);
JSONArray json_array = new JSONArray(json.getString("children"));
nestedChildren.add(json.getString("id"));
if ( json_array.length() > 0 ) {
findAllChild(json_array);
}
}
}
This assumes it is all Arrays, witch in my case it is