List item with double quotes - java

I want list item should be with double quotes.
i tried like this :
List<String> langList = new ArrayList<>();
for (Language obj : language) {
langList.add(obj.getCode());
}
JSONObject where = new JSONObject();
try {
JSONObject languages = new JSONObject();
languages.put("$in", langList);
where.put("languages", languages);
} catch (JSONException e) {
e.printStackTrace();
}
result of langList is : "[en, ta, hi]"
and I added double quotes for items using langList.add("\"" + obj.getCode() + "\"");
now, It returns the result is : "[\"en\", \"ta\", \"hi\"]"
I don't want outside double quotes also.
am expecting result is : ["en", "ta", "hi"]

I have added an extra " to both sides before adding them to the list. PFB the code snippet.
String array[] = new String[] {"en","ta", "hi"};
List<String> langList = new ArrayList<>();
for (String item : array) {
langList.add("\""+item+"\"");
}
System.out.println("langList: "+ langList);
try {
JSONArray jsonObject = new JSONArray(langList.toString());
System.out.println("jsonObject: "+jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
I could see below logs in console.
langList: ["en", "ta", "hi"]
jsonObject: ["en","ta","hi"]
Hope this helps.
Note: Used org.json.JSONArray and org.json.JSONException classes in above code.

You can simply use:
langList.add('"' + obj.getCode() + '"');

try this
List<String> langList = new ArrayList<>();
for (Language obj : language) {
langList.add('"'+obj.getCode()+'"');
}

Add double quotes for items using this:
List<String> langList = new ArrayList<>();
for (Language obj : language) {
langList.add('"'+obj.getCode()+'"');
}

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 iterate json String

I have an array of JSON strings like:
[{
"id":"BirthDate",
"field":"BirthDate",
"type":"date",
"input":"text",
"operator":"equal",
"value":"2016/04/07"
}]
I want to be able to iterate this array and want to get its id, field, value in Java
Using the below code I got an exception
"json object must begin with {"
String rules=helper.getRules();
System.out.println("====Rulses=====:"+rules);
try {
JSONObject obj = new JSONObject(rules);
System.out.println("====obj===="+obj);
// boolean error = obj.getBoolean("error");
String id = obj.getString("id");
System.out.println("===id is===: "+id);
} catch (JSONException e){
e.printStackTrace();
}
You should instead create a JSONArray from the String and then iterate over the array. Modify your code as
String rules=helper.getRules();
System.out.println("====Rulses=====:"+rules);
try {
// create the json array from String rules
JSONArray jsonRules = new JSONArray(rules);
// iterate over the rules
for (int i=0; i<jsonRules.length();i++){
JSONObject obj = jsonRules.get(i);
System.out.println("====obj===="+obj);
String id = obj.getString("id");
System.out.println("===id is===: "+id);
}
} catch (JSONException e){
e.printStackTrace();
}
Try this parsing your rulesinto a JSONArray:
String rules = "[{\"id\":\"BirthDate\",\"field\":\"BirthDate\",\"type\":\"date\",\"input\":\"text\",\"operator\":\"equal\",\"value\":\"2016/04/07\"}]";
try {
JSONArray obj = new JSONArray(rules); // parse the array
for(int i = 0; i < obj.length(); i++){ // iterate over the array
JSONObject o = obj.getJSONObject(i);
String id = o.getString("id");
System.out.println("===id is===: " + id);
}
} catch (JSONException e){
e.printStackTrace();
}
In the JSON you gave as example you just have one element in your array.

Get the JSONObject in the right order

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

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);
}

Categories