Get the JSONObject in the right order - java

I am using org.json library and am trying to create JSON Object stops in the simple form as below but I am always getting all timeEntries in the same JSONArray timeArray and the name is always changes in the stops as in the current output
Current output:
{"arrival_time":
{"mon-fri":[
["04:48","05:18","05:46","06:16"],
["04:52","05:22","05:50","06:20"],
["04:57","05:27","05:56","06:26"]
]
},
"stops_name":"third name"}
Code:
ArrayList<String> result = new ArrayList<String>();
JSONObject stops = new JSONObject();
JSONObject arrivals = new JSONObject();
JSONArray arrivalMoFr = new JSONArray();
for (Entry<String, List<String>> entry : map.entrySet()) {
String name = entry.getKey();
List<String> timeEntries = entry.getValue();
try {
stops.put("stops_name", name);
JSONArray timeArray = new JSONArray(timeEntries);
arrivalMoFr.put( timeArray);
arrivals.put("mon-fri", arrivalMoFr);
stops.put("arrival_time", arrivals);
System.out.println(stops.toString(3));
} catch (JSONException e) {
e.printStackTrace();
}
Simple how should the result like
{"arrival_time":
{"mon-fri":["04:48","05:18","05:46","06:16"]
}
"stops_name":"first name"},
{"arrival_time":
{"mon-fri":["04:52","05:22","05:50","06:20"]
}
"stops_name":"second name"},
{"arrival_time":
{"mon-fri":["04:57","05:27", "05:56","06:26"]
}
"stops_name":"third name"}

Keep in mind that you want an array as your root object. You'll have to create the other array and objects multiple times, so initializing them outside the for loop isn't useful.
ArrayList<String> result = new ArrayList<String>();
JSONArray stops = new JSONArray();
for (Entry<String, List<String>> entry : map.entrySet()) {
String name = entry.getKey();
List<String> timeEntries = entry.getValue();
try {
JSONObject stop = new JSONObject();
stop.put("stops_name", name);
JSONArray timeArray = new JSONArray(timeEntries);
//arrivalMoFr.put( timeArray);
JSONObject arrivals = new JSONObject();
arrivals.put("mon-fri", timeArray);
stop.put("arrival_time", arrivals);
stops.put(stop);
//System.out.println(stops.toString(3));
} catch (JSONException e) {
e.printStackTrace();
}
}

Related

How to get key from json object

I have the json array :
{"objets":{"1":"Question","2":"Response"},"success":true}
I want to test if the text selected on spinner exist in the array it will return the number (1 or 2).
Here is what I've done until now :
String responseContent = response.asString();
Log.d("OBJECTS", responseContent);
try {
JSONObject jobj = new JSONObject(responseContent);
JSONObject users = jobj.getJSONObject("objetcs");
Log.e("hello", String.valueOf(users));
if(users.toString().contains(spinner_objet.getSelectedItem().toString().trim())){
Log.e("hello", "it exist");
String user=users.getString("id");
Log.e("hello1", String.valueOf(user));
}
} catch (JSONException e1) {
e1.printStackTrace();
}
But I'm not getting any thing, can any one help me with this ?
You can parse your Json into a hashMap like so :
JSONObject object = new JSONObject();
Map<String,Integer> map = new HashMap<>();
while (object.keys().hasNext() ){
Integer key = (Integer) object.keys().next();
map.put((String) object.get(String.valueOf(key)), key);
}
You can then use the values of the map to put in the spinner.
map.values();
Whenever the user selects from the spinner, you can get the id from the map.

convert from list to json in java

I have a list and I want to convert it to json.
Here is my code
JqGridModel gridModel1 = new JqGridModel();
Date FromDate = new Date("1996-07-04");
Date ToDate = new Date("1996-07-05");
gridModel1.setOrderID(10248);
gridModel1.setFromDate(FromDate);
gridModel1.setToDate(ToDate);
gridModel1.setCustomerID("WILMK");
gridModel1.setShipName("Vins et alcools Chevalier");
JqGridModel gridModel2 = new JqGridModel();
Date FromDate2 = new Date("1996-07-04");
Date ToDate2 = new Date("1996-07-05");
gridModel2.setOrderID(10248);
gridModel2.setFromDate(FromDate2);
gridModel2.setToDate(ToDate2);
gridModel2.setCustomerID("WILMK");
gridModel2.setShipName("Vins et alcools Chevalier");
List jqGridModels = new ArrayList();
jqGridModels.add(gridModel1);
jqGridModels.add(gridModel2);
And I want to convert it to be in the following format:
{
"rows":[
{"OrderID":"10248","FromDate":"1996-07-04","CustomerID":"WILMK","ShipName":"Vins et alcools Chevalier","ToDate":"1996-07-05"},
{"OrderID":"10249","FromDate":"1996-07-05","CustomerID":"TRADH","ShipName":"Toms Spezialit\u00e4ten","ToDate":"1996-07-17"},
{"OrderID":"10250","FromDate":"1996-07-08","CustomerID":"HANAR","ShipName":"Hanari Carnes","ToDate":"1996-07-26"},
{"OrderID":"10251","FromDate":"1996-07-08","CustomerID":"VICTE","ShipName":"Victuailles en stock","ToDate":"1996-08-01"},
{"OrderID":"10252","FromDate":"1996-07-09","CustomerID":"SUPRD","ShipName":"Supr\u00eames d\u00e9lices","ToDate":"1996-08-01"}
]
}
Any help would be greatly appreciated.
Firstly: use generics
List jqGridModels = new ArrayList(); //bad
List<JqGridModel> jqGridModels = new ArrayList<>(); //good
Secondly: Can you use Gson?
List<JqGridModel> jqGridModels = new ArrayList<>();
Gson gson = new Gson();
JsonElement jsElem = gson.toJsonTree(jqGridModels, new TypeToken<List<JqGridModel>>() {}.getType());
if (! jsElem.isJsonArray()) {
//this is an error...
}
JsonArray jsonArray = jsElem.getAsJsonArray();
Haven't tested it yet but it should work, I'm doing this in my project and it's ok, if you have more troubles please tell me!
If you want to do it manually you can :
Create a method to generate the JSON from tour object :
class JqGridModel{
public JSONObject toJSON(){
JSONObject json = new JSONObject();
json.accumulate("OrderID", orderID);
// DO the same for all attributes
return json;
}
}
And then call this method looping on the list content :
JSONObject json = new JSONObject();
JSONArray arr = new JSONArray();
for(JqGridModel m: jqGridModels){
arr.put(m.toJSON());
}
json.accumulate("rows", arr);
com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
StringBuffer result = new StringBuffer("{\n\t\"rows\":[\n");
try {
for(Object item : jqGridModels){
result = result.append("\t\t\t");
result = result.append(mapper.writeValueAsString(item));
result = result.append("\n");
}
if(jqGridModels.size() > 1){
result = result.append("\t]\n}");
System.out.print(result);
}
} catch (JsonProcessingException e) {
e.printStackTrace();
}

How to get dynamically changed Key's value in Json String using java

I'm trying to parse Json string using java, I have stuck up with some scenario.
See below is my JSON String:
"NetworkSettings": {
"Ports": {
"8080/tcp": [ // It will change dynamically like ("8125/udp" and "8080/udp" etc....)
{
"HostIp": "0.0.0.0",
"HostPort": "8080"
}
]
}
}
I try to parse the above json string by using the following code:
JsonObject NetworkSettings_obj=(JsonObject)obj.get("NetworkSettings");
if(NetworkSettings_obj.has("Ports"))
{
JsonObject ntw_Ports_obj=(JsonObject)NetworkSettings_obj.get("Ports");
if(ntw_Ports_obj.has("8080/tcp"))
{
JsonArray arr_ntwtcp=(JsonArray)ntw_Ports_obj.get("8080/tcp");
JsonObject ntwtcp_obj=arr_ntwtcp.get(0).getAsJsonObject();
if(ntwtcp_obj.has("HostIp"))
{
ntw_HostIp=ntwtcp_obj.get("HostIp").toString();
System.out.println("Network HostIp = "+ntw_HostIp);
}
if(ntwtcp_obj.has("HostPort"))
{
ntw_HostPort=ntwtcp_obj.get("HostPort").toString();
System.out.println("Network HostPort = "+ntw_HostPort);
}
}
else
{
ntw_HostIp="NA";
ntw_HostPort="NA";
}
}
else
{
ntw_HostIp="NA";
ntw_HostPort="NA";
}
In my code I have used this code
JsonArray arr_ntwtcp=(JsonArray)ntw_Ports_obj.get("8080/tcp");
to get the value of "8080/tcp"
How can I get the values of dynamically changing key like ("8125/udp","8134/udp", etc...)
Note: I'm using gson library for parsing
After modification
public static void main(String args[])
{
try
{
JsonParser parser = new JsonParser();
JsonObject obj=(JsonObject)parser.parse(new FileReader("sampleJson.txt"));
System.out.println("obj = "+obj);
JsonObject NetworkSettings_obj=(JsonObject)obj.get("NetworkSettings");
if(NetworkSettings_obj.has("Ports"))
{
JsonObject ntw_Ports_obj=(JsonObject)NetworkSettings_obj.get("Ports");
System.out.println("ntw_Ports_obj = "+ntw_Ports_obj);
Object keyObjects = new Gson().fromJson(ntw_Ports_obj, Object.class);
List keys = new ArrayList();
System.out.println(keyObjects instanceof Map); //**** here the statement prints false
if (keyObjects instanceof Map) // *** so controls doesn't enters into the if() condition block *** //
{
Map map = (Map) keyObjects;
System.out.println("Map = "+map);
keys.addAll(map.keySet());
String key = (String) keys.get(0);
JsonArray jArray = (JsonArray) ntw_Ports_obj.get(key);
System.out.println("Array List = "+jArray);
}
}
}
catch(Exception e)
{
}
}
You can do something like that (not tested but should be ok) :
if (ntw_Ports_obj.isJsonArray()) {
Iterator it = ntw_Ports_obj.getAsJsonArray().iterator();
while (it.hasNext()) {
JsonElement element = (JsonElement) it.next();
if(element.isJsonArray()){
JsonArray currentArray = element.getAsJsonArray();
// Do something with the new JsonArray...
}
}
}
So your problem is the key 8080/tcp is not fixed and it may change. when this situation you can try like this to get the value of the Dynamic key.
Set<Map.Entry<String, JsonElement>> entrySet = ntw_Ports_obj
.entrySet();
for (Map.Entry<String, JsonElement> entry : entrySet) {
String key = entry.getKey();
JsonArray jArray = (JsonArray) ntw_Ports_obj.get(key);
System.out.println(jArray);
}
Edit:
Object keyObjects = new Gson().fromJson(ntw_Ports_obj, Object.class);
List keys = new ArrayList();
/** for the given json there is a one json object within the 'Ports' so the 'keyObjects' will be the 'Map'**/
if (keyObjects instanceof Map) {
Map map = (Map) keyObjects;
keys.addAll(map.keySet());
/**
* keys is a List it may contain more than 1 value, but for the given
* json it will contain only one value
**/
String key = (String) keys.get(0);
JsonArray jArray = (JsonArray) ntw_Ports_obj.get(key);
System.out.println(jArray);
}

Needed to parse JSON Objects Present under LinkedList and calculate a field value

I have got a Map with a key and a list of JSONObjects as shown
Map<String, LinkedList<JSONObject>> vendorOrdersMap = new LinkedHashMap<String, LinkedList<JSONObject>>();
I need to calculate price present under each LinkedList of a Vendor , to know which vendor has got the highest price .
Map<String, LinkedList<JSONObject>> vendorOrdersMap = new LinkedHashMap<String, LinkedList<JSONObject>>();
// For Vendor 1
JSONObject vendor1 = new JSONObject();
vendor1.put("price", "100");
JSONObject vendor2 = new JSONObject();
vendor2.put("price", "200");
LinkedList<JSONObject> list1vendor1 = new LinkedList<JSONObject>();
list1vendor1.add(vendor1);
list1vendor1.add(vendor2);
// For Vendor2
JSONObject vendor3 = new JSONObject();
vendor1.put("price", "200");
JSONObject vendor4 = new JSONObject();
vendor2.put("price", "300");
LinkedList<JSONObject> list1vendor2 = new LinkedList<JSONObject>();
list1vendor2.add(vendor3);
list1vendor2.add(vendor4);
// Add them to the Map
vendorOrdersMap.put("Vendor1", list1vendor1);
vendorOrdersMap.put("Vendor2", list1vendor2);
//I started with this but couldn't able to proceed further with this
for (Map.Entry<String, LinkedList<JSONObject>> entry : vendorOrdersMap.entrySet())
{
String key = entry.getKey();
LinkedList<JSONObject> jsonobj = entry.getValue();
}
Your last line was:
LinkedList<JSONObject> jsonobj = entry.getValue();
After this, iterate over list again like:
for(JSONObject obj : jsonobj) {
Then get values out of JSONObject like:
String price = obj.getString("price");
Then do your comparison to calculate highest price.

How can i sort my JSON object based on Key?

I am creating a JSON object in which i am adding a key and a value which is an array. The value for both key and value comes from a TreeSet which has data in sorted form. However, when I insert data in my json object, it is stored randomly without any order.
This is my json object currently:
{
"SPAIN":["SPAIN","this"],
"TAIWAN":["TAIWAN","this"],
"NORWAY":["NORWAY","this"],
"LATIN_AMERICA":["LATIN_AMERICA","this"]
}
and my code is:
Iterator<String> it= MyTreeSet.iterator();
while (it.hasNext()) {
String country = it.next();
System.out.println("----country"+country);
JSONArray jsonArray = new JSONArray();
jsonArray.put(country);
jsonArray.put("this);
jsonObj.put(country, jsonArray);
}
Is there any way I can store the data into my json object inside the while loop itself?
Even if this post is quite old, I thought it is worth posting an alternative without GSON:
First store your keys in an ArrayList, then sort it and loop through the ArrayList of keys:
Iterator<String> it= MyTreeSet.iterator();
ArrayList<String>keys = new ArrayList();
while (it.hasNext()) {
keys.add(it.next());
}
Collections.sort(keys);
for (int i = 0; i < keys.size(); i++) {
String country = keys.get(i);
System.out.println("----country"+country);
JSONArray jsonArray = new JSONArray();
jsonArray.put(country);
jsonArray.put("this");
jsonObj.put(country, jsonArray);
}
It works with Google Gson API. Try it out.
try{
TreeSet<String> MyTreeSet = new TreeSet<String>();
MyTreeSet.add("SPAIN");
MyTreeSet.add("TAIWNA");
MyTreeSet.add("INDIA");
MyTreeSet.add("JAPAN");
System.out.println(MyTreeSet);
Iterator<String> it= MyTreeSet.iterator();
JsonObject gsonObj = new JsonObject();
JSONObject jsonObj = new JSONObject();
while (it.hasNext()) {
String country = it.next();
System.out.println("----country"+country);
JSONArray jsonArray = new JSONArray();
jsonArray.put(country);
jsonArray.put("this");
jsonObj.put(country, jsonArray);
JsonArray gsonArray = new JsonArray();
gsonArray.add(new JsonPrimitive("country"));
gsonArray.add(new JsonPrimitive("this"));
gsonObj.add(country, gsonArray);
}
System.out.println(gsonObj.toString());
System.out.println(jsonObj.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Below are what the doc says from http://www.json.org/java/index.html.
"A JSONObject is an unordered collection of name/value pairs."
"A JSONArray is an ordered sequence of values. "
In order to get an sorted Json Object, you can use Gson which is already provided a good answer by #user748316.

Categories