How to convert int to json in java - java

How can I convert an int to a JSON in java.
A simple Example:
int number = 5;
Gson gson = new Gson();
String numbersJson = gson.toJson(number);
return number;
but this is not working :( because i got 5 as returned value.
I want the json format: {"number": 5} as value

If you want a key-value, then either wrap to an Object or a Map:
Map<String, Integer> number = new HashMap<>();
number.put("number", 5);
String numbersJson = gson.toJson(number);

Just number 5 in json will be 5. What you need is an object with property number that has value of 5
JsonObject json = new JsonObject();
json.addProperty("number", 5);
String jsonAsString = json.toString(); // If you want it as string
System.out.println(jsonAsString); // prints {"number":5}

Related

Convert {key=value, key=value} to {"key":"value", "key":"value"}

I have a string that is being returned by an API which looks like this :
String result1 = "{username=null, tokenCode=00000000-0000-0000-0000-0000754d6034}";
I converted this to
String result2 = "{"username":"null", "tokenCode":"00000000-0000-0000-0000-0000754d6034"}";
Below is the code I am using it to convert to result2 from result1.
String result2 = new GsonBuilder().serializeNulls().create().toJson(result1);
Again I am doing this to make it a JSON object from String.
JSONObject jsonObject = new JSONObject(result2);
Is there a better way I can directly convert the "result1" to JSONObject without having to convert it to "result2".

How to return the more than two map objects in Java

Actually I am trying to parse the two api's json data in the same class. I know it should not be done but this is the requirement.
I am getting data from the hashmap. And I want to add it in the table.But the problem is program adds only last item in table. but while debugging it's giving all values.
Here is my code:
public class services2
{
public Map<Object, Object> getReportees(String idOfEmp) throws Exception {
......
if(resp.getStatus() != 200){
System.err.println("Unable to connect to the server");
}
String output = resp.getEntity(String.class);
//Store the JSON objects in an array
//Get the index of the JSON object and print the values as per the index
JSONParser parse = new JSONParser();
JSONObject jobj = (JSONObject)parse.parse(output);
JSONArray jsonarr_1 = (JSONArray) jobj.get("list");
Map<Object, Object> map=new HashMap<Object,Object>();
for(int i=0;i<jsonarr_1.size();i++){
JSONObject jsonobj_1 = (JSONObject)jsonarr_1.get(i);
JSONObject jive = (JSONObject)jsonobj_1.get("jive");
String var = jive.get("username").toString();
values = var;
if(resp1.getStatus() != 200){
system.err.println("Unable to connect to the server");
}
String output1 = resp1.getEntity(String.class);
JSONObject jobjs = (JSONObject) new JSONParser().parse(output1);
JSONArray jsonarr_11 = (JSONArray) jobjs.get("issues");
System.out.println("count"+jsonarr_11.size());
Object obj3 = jsonarr_11.size();
int counter = (Integer) obj3;
System.out.println(counter);
Object obj1 = jsonobj_1.get("displayName");
Object obj2 = jive.get("username");
map.put(obj1, obj2);
map.put("obj3", obj3);
System.out.println(obj3);
}
return map; //for the map obj3 return only the last count that is 1
}
}
Here when I am trying to send the map obj3. I am getting only the last value. I actually want the count in a correct way.
This is the output:
Number id username count
1 A12345 Anagha R 1
2 M12345 Madhusudan S 1
3 AT12345 Amreen Taj 1
Expected output is:
1 A12345 Anagha R 0
2 M12345 Madhusudan S 0
3 AT12345 Amreen Taj 1
When I am trying to print in the console it is giving me the right count but when I am trying through the map it is sending only the last value that is count 1.
You can try using a list of a map like the following:
List<HashMap<Object,Object>>
The problem is in below line of code:
map.put("obj3", obj3);
Each time you are replacing the value for "Obj3" instead of incrementing the existing value of the map.
Instead what you need to do is:
if(map.containsKey("obj3")
{
Object obj3 = map.get("obj3");
//put your logic of incrementing or adding the count
//Lets say it is new Value
map.put("obj3",newValue)
}

How to create JSON in Android?

I want to create a JSON string like this:
[{"addon_id":2,"addon_rate":1550},{"addon_id":3, "addon_rate":300}]
Is this possible? How?
My code as it stands:
String formattedString = BookingDetailsCartAdapter.addones_id.toString().replace("[", "").replace("]", "").trim();
String formattedString1 = BookingDetailsCartAdapter.addones_rate.toString().replace("[", "").replace("]", "").trim();
myjson="[{\"addon_id\":\""+formattedString+"\",\"addon_rate\":\""+formattedString1+"\"}]";
Your JSON means that it's an array which contains two objects with the keys addon_id and addon_rate. Both accept a number/integer as value. First you need to create a JSONArray which holds several JSONObjects. Then you have to create the JSONObjects which set your keys and values. After this you need to add those objects to your array. Your jsonArray contains the string above as soon as you print/toString() it
JSONArray jsonArray = new JSONArray();
JSONObject jsonObjOne = new JSONObject();
jsonObjOne.put("addon_id", 2);
jsonObjOne.put("addon_rate", 1550);
JSONObject jsonObjTwo = new JSONObject();
jsonObjTwo.put("addon_id", 3);
jsonObjTwo.put("addon_rate", 300);
jsonArray.put(jsonObjOne);
jsonArray.put(jsonObjTwo);
You can use GSON
Add in Gradle file
compile 'com.google.code.gson:gson:2.8.1'
public class Addon{
public int addon_id;
public int addon_rate;
}
Addon addon = new Addon ();
addon.addon_id=2;
addon.addon_id=1550;
Gson gson = new Gson();
String json = gson.toJson(addon); //
//--- For array
List<Addon > objList = new ArrayList<Addon >();
objList.add(new Addon (0, 1550));
objList.add(new Addon (1, 1552));
objList.add(new Addon (2, 1553));
String json = new Gson().toJson(objList);
System.out.println(json);
http://www.javacreed.com/simple-gson-example/

double quotes found in json array

a json array is as given below
var data = [
{label:'gggg',data: [[(new Date('2011/12/01')).getTime(),53914],[(new Date('2012/1/02')).getTime(),32172],[(new Date('2012/2/03')).getTime(),824],[(new Date('2012/4/04')).getTime(),838],[(new Date('2012/6/05')).getTime(),755],[(new Date('2012/7/06')).getTime(),0],[(new Date('2012/8/07')).getTime(),0],[(new Date('2012/9/08')).getTime(),0],[(new Date('2012/10/09')).getTime(),0],[(new Date('2012/11/10')).getTime(),0],[(new Date('2012/12/11')).getTime(),0],[(new Date('2012/12/11')).getTime(),0]]}
];
in java class for creating the above similar json, i'm using the following code given below.
but the problem is there is a double quotes in each "(new Date(2012/12/01)).getTime()"
can anyone please tell me how to remove those double quotes
Query q1=session.createQuery("FROM VendorMonth");
List li1=q1.list();
String supname="",tempsupname;
JSONObject obj = new JSONObject();
JSONArray jsonarrmast = new JSONArray();
List s=new ArrayList();
JSONArray finals=new JSONArray();
JSONArray finalarray = new JSONArray();
for(int i=0;i<li1.size();i++)
{
HashMap hmap = new HashMap();
VendorMonth venmonth=(VendorMonth) li1.get(i);
tempsupname=venmonth.getId().getSupplierName();
if(i==0){
supname=venmonth.getId().getSupplierName();
}
if(!supname.equals(tempsupname)){
obj.put("label", supname);
obj.put("data", jsonarrmast);
jsonarrmast = new JSONArray();
s.add(obj);
finalarray.put(obj);
obj = new JSONObject();
supname=venmonth.getId().getSupplierName();
JSONArray jsonarr = new JSONArray();
String date=venmonth.getId().getYearnam()+"/"+venmonth.getId().getMonthnam()+"/01";
String ss=new String("(new Date("+date+")).getTime()");
jsonarr.put(ss);
jsonarr.put(venmonth.getId().getRentalrate());
jsonarrmast.put(jsonarr);
}
else
{
JSONArray jsonarr = new JSONArray();
String date=venmonth.getId().getYearnam()+"/"+venmonth.getId().getMonthnam()+"/01";
String ss=new String("(new Date("+date+")).getTime()");
jsonarr.put(ss);
jsonarr.put(venmonth.getId().getRentalrate());
jsonarrmast.put(jsonarr);
}
if(i==(li1.size()-1)){
obj.put("label", supname);
obj.put("data", jsonarrmast);
jsonarrmast = new JSONArray();
s.add(obj);
finalarray.put(obj);
}
}
but i'm getting the output as given below
[{"data":[["(new Date(2012/12/01)).getTime()",10976.23],["(new Date(2013/1/01)).getTime()",51213.8200000002],["(new Date(2013/2/01)).getTime()",32172.31],["(new Date(2013/3/01)).getTime()",824.600000000001],["(new Date(2013/4/01)).getTime()",838.000000000001],["(new Date(2013/5/01)).getTime()",755.780000000001],["(new Date(2013/6/01)).getTime()",50877.12]],"label":"Weather Ford"},{"data":[["(new Date(2012/12/01)).getTime()",24368.3],["(new Date(2013/1/01)).getTime()",1968.76]],"label":"Logan Tools"},{"data":[["(new Date(2012/12/01)).getTime()",3425.63],["(new Date(2013/1/01)).getTime()",731.75]],"label":"Pioneer tools"}]
You're not going to be able to create a JSON object that matches your declaration, because that's not a JSON object: it's Javascript code.
Once that Javascript code is ran, however, data will contain an object that can be serialized to JSON, and I'm assuming that's what you're trying to achieve.
What your Java code does is add a String to a BasicDBArray - the fact that it's interpreted as a String should not come as a surprise. By the same token, when you add an int or a boolean, they're added as ints and booleans, not strings.
What you actuall want to put in your BasicDBArray is the value that new Date('2011/12/01').getTime() would return if interpreted as Javascript: the number of milliseconds between 1970/01/01 and 2011/12/01. I'm assuming you can retrieve that through something like venmonth.getId().getDate().getTime(), or however it is you retrieve a Date instance from your venmonth object.

Parse JSON object with string and value only

I have problem when trying to parse with minimum value to map in Android.
There some sample JSON format with more information ex:
[{id:"1", name:"sql"},{id:"2",name:"android"},{id:"3",name:"mvc"}]
This that example most common to use and easy to use just use getString("id") or getValue("name").
But how do I parse to map using this JSON format with just only string and value minimum format to java map collection using looping. And because the string json will always different one with another. ex:
{"1":"sql", "2":"android", "3":"mvc"}
Thank
You need to get a list of all the keys, loop over them and add them to your map as shown in the example below:
String s = "{menu:{\"1\":\"sql\", \"2\":\"android\", \"3\":\"mvc\"}}";
JSONObject jObject = new JSONObject(s);
JSONObject menu = jObject.getJSONObject("menu");
Map<String,String> map = new HashMap<String,String>();
Iterator iter = menu.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = menu.getString(key);
map.put(key,value);
}
My pseudocode example will be as follows:
JSONArray jsonArray = "[{id:\"1\", name:\"sql\"},{id:\"2\",name:\"android\"},{id:\"3\",name:\"mvc\"}]";
JSON newJson = new JSON();
for (each json in jsonArray) {
String id = json.get("id");
String name = json.get("name");
newJson.put(id, name);
}
return newJson;

Categories

Resources