Put String value in gson.JsonArray [duplicate] - java

This question already has answers here:
How to add a String Array in a JSON object?
(5 answers)
Closed 6 years ago.
I want to store a String in a JsonArray.
Ex:
"virtual_hosts": [ "some_host"]
How should I do this, with the help of java.
JsonArray arr = new JsonArray();
arr.add()
This only lets me add a JsonObject, but I want to store a String.

If you are going to use gson by google, looks like you have to do it this way:
JsonPrimitive firstHost = new JsonPrimitive("vlbr-vlbre9ef7a820b3f43c7bd3418bb62.uscom-central-1.c9dev1.oc9qadev.com");
JsonArray jArray = new JsonArray();
jArray.add(firstHost);
JsonObject jObj = new JsonObject();
jObj.add("virtual_hosts", jArray);
The first line converts your java string into a json string.
In the next two steps, a json array is created and your string is added to it.
After that, a json object which is going to hold the array is created and the array is added with a key that makes the array accessible.
If you inspect the object, it looks exactly like you want to have it.
There is no simple way in adding just a string to an JsonArray if you want to use gson. If you need to add your string directly, you probably have to use another library.

You can create a list of hosts and set the property in JSON.
import org.json.simple.JSONObject;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<String> hosts = new ArrayList<String>();
hosts.add("vlbr-vlbre9ef7a820b3f43c7bd3418bb62.uscom-central-1.c9dev1.oc9qadev.com");
hosts.add("dummy.oc9qadev.com");
JSONObject jsonObj = new JSONObject();
jsonObj.put("virtual_hosts", hosts);
System.out.println("Final JSON String is--"+jsonObj.toString());
}
}
Output -
{ "virtual_hosts":
["vlbr-vlbre9ef7a820b3f43c7bd3418bb62.uscom-central-1.c9dev1.oc9qadev.com",
"dummy.oc9qadev.com"] }

What you are trying to do is storing a JSONArray into a JSONObject. Because the key virtual_hosts is going to contain a value as JSONArray.
Below code can help you.
public static void main( String[] args ) {
JSONArray jsonArray = new JSONArray();
jsonArray.add( "vlbr-vlbre9ef7a820b3f43c7bd3418bb62.uscom-central-1.c9dev1.oc9qadev.com" );
JSONObject jsonObject = new JSONObject();
jsonObject.put( "virtual_hosts", jsonArray );
System.out.println( jsonObject );
}
Output:
{"virtual_hosts":["vlbr-vlbre9ef7a820b3f43c7bd3418bb62.uscom-central-1.c9dev1.oc9qadev.com"]}
Maven dependecny
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>

Related

How can i convert this JSON to Java Object?

I'm learning JACKSON. To train my skills i want to get field "URL" from following JSON:
How can i do that? I don't need whole JSON-object, just one field (URL).
You don't need to convert the JSON into a Java Object for that you will need to define POJOS.
Maybe this will help :-
final ObjectNode yourNode = new ObjectMapper().readValue(<Your_JSON_Input_String>, ObjectNode.class);
if (node.has("URL")) {
System.out.println("URL :- " + node.get("URL"));
}
import org.json.JSONArray;
import org.json.JSONObject;
public class Main {
public static void main(String[] args) throws IOException {
String jsonString = "{\"data\":[{\"url\":\"http://example.com\"}]}";
JSONObject jsonObject = new JSONObject(jsonString); // 1
JSONArray data = jsonObject.getJSONArray("data"); // 2
JSONObject objectAtIndex0 = data.getJSONObject(0); // 3
String urlAtObject0 = objectAtIndex0.getString("url"); // 4
System.out.println(urlAtObject0);
}
}
Get JSON object for whole JSON string
Get data as JSON array
Get JSON object at desired index or loop on JSON array of previous step
Get url field of the JSON object

How to set array value in the jsonobject

I am getting the array values as
I need to construct the object as jsonObject.
So I have added like below but the returning object as an error.
How can I add the array as expected in the users.
Note: Here I am sending the users in array from a fragment to set the values in my payload
private String mUserArray; //value =["user1", "user2"]
mUserArray is added in the constructor.
final JsonArray array = new JsonArray();
array.add(mUserArray1);
final JsonObject jo = new JsonObject();
jo.addProperty("type", "value")
jo.add("usernames" , array); // If i set the userarray it failed to convert Added like this as well//new JsonPrimitive(mUserArray1)
return jo;
Expected Result:
{"type": "value", "usernames":["user1", "user2"]}
Actual Result:
{"type":"value","usernames":"[\"user1\", \"user2\"]"}
It seems like that you added the usernames property as a string literal rather than as a JSON array. You can construct a JsonArray of strings from a Java array the following way.
String[] userArray = {"user1", "user2"};
JsonArray userJsonArray = new JsonArray();
for(String user: userArray){
userJsonArray.add(new JsonPrimitive(user));
}
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("type", "value");
jsonObject.add("usernames", userJsonArray);
Note that JsonObject::addProperty only adds primitives to the JSON object rather than arrays or objects.

How to get JSON values in to String array using Java? [duplicate]

This question already has answers here:
Converting JSON data to Java object
(14 answers)
Closed 9 years ago.
I have a Java Rest API #PUT. Which is receiving the json data as shown in below format
["name1,scope1,value1","name2,scope2,value2"]
I am getting this value in my Java API method as
(String someList)
someList will contain ["name1,scope1,value1","name2,scope2,value2"]
How to get these values ("name1,scope1,value1" and "name2,scope2,value2") in String array?
Using the org.json package, this would do (assuming response as String in responseString):
JSONArray myJSON = new JSONArray(responseString);
String[] myValues = new String[myJSON.length];
for(int i=0; i<myValues.length; i++) {
myValues[i] = myJSON.getString(i);
}
If you then want to split up the strings in myValues[] using ',' as a separator, you can do:
String[] innerArray = myValues[i].split(",");
An example JSON code :
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.ParseException;
import org.json.simple.parser.JSONParser;
class JsonDecodeDemo
{
public static void main(String[] args)
{
JSONParser parser=new JSONParser();
String s = "[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
System.out.println("s = " + s);
try{
Object obj = parser.parse(s);
JSONArray array = (JSONArray)obj;
System.out.println("The 2nd element of array");
System.out.println(array.get(1));
System.out.println();
JSONObject obj2 = (JSONObject)array.get(1);
System.out.println("Field \"1\"");
System.out.println(obj2.get("1"));
s = "{}";
obj = parser.parse(s);
System.out.println(obj);
s= "[5,]";
obj = parser.parse(s);
System.out.println(obj);
s= "[5,,2]";
obj = parser.parse(s);
System.out.println(obj);
}catch(ParseException pe){
System.out.println("position: " + pe.getPosition());
System.out.println(pe);
}
}
}
You can refer to this.
You could put the parts into an array of String with just one line:
String[] parts = someList.replaceAll("^\\[\"|\"\\]$", "").split("\",\"");
The call to replaceAll() strips off the leading and trailing JSON adornment and what's left is split on what appears between the target parts, ie ","
Note that due to the flexible nature of valid json, it would be safer to use a JSON library than this "string based" approach. Use this only if you can't use a json library.

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.

Create a JSONArray

How can I create a JSONArray, since creating a JSONObject is quite simple:
JSONObject j = new JSONObject();
j.put("key",value);
Right now I can put another string in the JSONObject, or a string representation of a JSONObject.
But how can I create a JSONArray and insert it to the JSONObject?
But how can I create a JSONArray and insert it to the JSONObject?
You can create JSONArray same like you have tried to create JSONObject.
Creating time:
For example:
JSONArray myArray = new JSONArray();
JSONObject j = new JSONObject();
j.put("key",value);
j.put("array",myArray);
Retrieving time:
you can fetch the value of String or JSONObject or any by their key name. For example:
JSONArray myArray = objJson.getJSONArray("array");
You can do it like:
String[] data = {"stringone", "stringtwo"};
JSONArray json = new JSONArray(Arrays.toString(data));
Or, create a JSONArray object and use the put method(s) to add any Strings you want. To output the result, just use the toString() method.
Why dont you use Gson library its very easy to convert any object into json array, json object
Download Gson library then use like
Gson gson=new Gson();
String json=gson.toJson(object);
if Object is of List object it will create json array
Gson gson = new Gson();
reverse parsing for array --
listObject = gson.fromJson(json,
new TypeToken<List<ClassName>>() {
}.getType());
for single object
object = gson.fromJson(json, ClassName.class);

Categories

Resources