I'm parsing a JsonObject with gson library using maven dependencies
but I can not have a map containing the keys and values.
I tried with the keyset method but it does not find the correspondence with the value (null pointer exception error) the JSONArray fields reprensent the array that i want to get but currentJsonObject.get("fields")
return an object that i cant parse to get the other key values.
this is the result of object which i get it from the object return by get("fields")
To summarize I want to parse the JSONArray fields and retrieve the value key from this array
JsonReader jsonReader = new JsonReader(new InputStreamReader(new FileInputStream("filename"), StandardCharsets.UTF_8));
jsonReader.beginArray();
Gson gson = new GsonBuilder().create();
Collection<String> list ;
Collection<String> keys ;
BasicDBObject map = new BasicDBObject();
while (jsonReader.hasNext()) {
JSONObject currentJsonObject = gson.fromJson(jsonReader,
JSONObject.class);
System.out.println(currentJsonObject.get("fields"));
}
jsonReader.close();
Json :
The below code might help you:
public String parse(String jsonLine) {
JsonElement jelement = new JsonParser().parse(jsonLine);
JsonObject jobject = jelement.getAsJsonObject();
jobject = jobject.getAsJsonObject("data");
JsonArray jarray = jobject.getAsJsonArray("translations");
jobject = jarray.get(0).getAsJsonObject();
String result = jobject.get("translatedText").getAsString();
return result;
}
Can someone provide me java code to create a json object as shown below
{"main":[
["one","two","three","four","five"],
["one","two","three","four","five"],
["one","two","three","four","five"],
["one","two","three","four","five"],
["one","two","three","four","five"]
]}
I have tried something like
Gson gson = new Gson();
JsonArray array = new JsonArray();
array.add(new JsonPrimitive("One"));
array.add(new JsonPrimitive("two"));
array.add(new JsonPrimitive("three"));
array.add(new JsonPrimitive("four"));
array.add(new JsonPrimitive("five"));
JsonObject jsonObject = new JsonObject();
jsonObject.add("main", array);
I am getting the result like below even when I am looping
{"main":["one","two","three","four","five"]}
like a single object. But I am expecting the result like
{"main":[
["one","two","three","four","five"],
["one","two","three","four","five"],
["one","two","three","four","five"],
["one","two","three","four","five"],
["one","two","three","four","five"]
]}
Many thanks in advance.
try this code to create json
Gson gson = new Gson();
JsonArray array = new JsonArray();
JsonArray child = new JsonArray();
child.add(new JsonPrimitive("One"));
child.add(new JsonPrimitive("two"));
child.add(new JsonPrimitive("three"));
child.add(new JsonPrimitive("four"));
child.add(new JsonPrimitive("five"));
for(int i=0;i<5;i++)
array.add(child);
JsonObject jsonObject = new JsonObject();
jsonObject.add("main", array);
System.out.println(jsonObject);
Assuming you're using Gson, this isn't the way it was designed to be used. Though this way is supported, it is not suggested, as you could use any json library to do this (SimpleJson).
Instead, Gson is able to directly serialize java objects we are familiar with, so you should represent your json object as a java object. JsonObject maps to a Map. JsonArray maps to List or an array. JsonPrimitives are mapped to their respective java primitive types (boolean, double, string, null)
// generate the object
Map<List<List<String>>> object = new HashMap<>();
List<List<String>> main = new ArrayList<>();
List<String> counts = Arrays.asList("one", "two", "three", "four", "five");
for (int i = 0; i < 5; i++) {
main.add(counts);
}
object.put("main", main);
// serialize it
String json = new Gson().toJson(object);
// deserializing it requires a typetoken or separate class representing the map object.
Map<List<List<String>>> desObj = new Gson().fromJson(json, new TypeToken<Map<List<List<String>>>>(){}.getType());
It appears "main" contains an array of arrays, so all you would have to do is add your array five times to another new array (e.g. call it mainArray) and then add mainArray to your jsonObject:
Create a new empty array: mainArray
Add array five times to mainArray
Add mainArray to jsonObject
You can try to convert the string representing your json data to JsonObject:
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class JsonQuestion {
public static void main(String[] args) {
String myJSON = "{\"main\":[\n"
+ " [\"one\",\"two\",\"three\",\"four\",\"five\"],\n"
+ " [\"one\",\"two\",\"three\",\"four\",\"five\"],\n"
+ " [\"one\",\"two\",\"three\",\"four\",\"five\"],\n"
+ " [\"one\",\"two\",\"three\",\"four\",\"five\"],\n"
+ " [\"one\",\"two\",\"three\",\"four\",\"five\"]\n"
+ "]}";
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = (JsonObject) jsonParser.parse(myJSON);
System.out.println("jsonObject: " + jsonObject.toString());
}
}
Gson gson = new Gson();
JsonArray array = new JsonArray();
array.add(new JsonPrimitive("One"));
array.add(new JsonPrimitive("two"));
array.add(new JsonPrimitive("three"));
array.add(new JsonPrimitive("four"));
array.add(new JsonPrimitive("five"));
JsonObject jsonObject = new JsonObject();
JsonArray marray = new JsonArray();
marray.add(array);
marray.add(array);
marray.add(array);
marray.add(array);
marray.add(array);
jsonObject.add("main", marray);
You can use below method to make json :
private void createJsonData(){
final String[] units = {"One","Two","Three","Four",
"Five"};
try {
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
JSONArray jsonArray1 = new JSONArray();
for (int j = 0; j < 5 ; j++) {
jsonArray1.put(units[j])
}
jsonArray.put(jsonArray);
jsonObject.put("main",jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
}
Use this method
public static void newjson() {
JSONObject json =new JSONObject();
List<List<String>> listoflist = new ArrayList<List<String>>();
List<String> list=new ArrayList<String>();
list.add("one");
list.add("one");
list.add("one");
listoflist.add(list);
listoflist.add(list);
try {
json.put("main",listoflist);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(json);
}
JSONObject jsonObj = new JSONObject("string");
jsonObj.toString();
"employees":[{"firstname":"stack","lastname":"overflow"}, {"firstname":"Happy","lastname":"Coding"}]
How can I append:
{"firstname":"Gloomy","lastname":"Sunday"}
to above json object
I want to get
"employees":[{"firstname":"stack","lastname":"overflow"}, {"firstname":"Happy","lastname":"Coding"}, {"firstname":"Gloomy","lastname":"Sunday"}]
upon jsonObj.toString();
Please do research this yourself first, this website is not here to do your computer science homework for you. Just cause I need some rep...
public class ex{
void example(){
try{
JSONObject jobj = new JSONObject("[{firstname:stack,lastname:overflow}]");
JSONObject jobj2 = new JSONObject("[{firstname:Happy,lastname:Coding}]");
JSONArray jarray = new JSONArray();
jarray.put(jobj);
jarray.put(jobj2);
}catch(JSONException e){
e.printStackTrace();
}
}
}
JSONObject jsonObj = new JSONObject();
JSONObject jo1 = new JSONObject("{"firstname":"Gloomy","lastname":"Sunday"}");
jsonObj.append("employees", jo1);
My String array has the following output each time it iterates through the loop
apple
orange
I want to convert my string array output to json format/jsonarray. I tried but it gives output as
{"fruits",apple}
{"fruits",orange}
I want my output as
{"fruits": [
{
"1": "apple"
}
{
"2": "orange"
}
I tried the below code
String[] strArray = new String[] {newString};
JSONObject json=new JSONObject();
//json.put("fruits", newString);
//System.out.println(json);
for(int i=0;i<strArray.length;i++)
{
System.out.print(strArray[i]+"\t");
json.put("",strArray[i]);
}
JSONObject obj = new JSONObject();
JSONArray array = new JSONArray();
for(int i=0;i<strArray.length;i++)
{
JSONObject fruit = new JSONObject();
fruit.put(""+i,strArray[i]);
array.put(fruit);
}
obj.put("Fruits",array);
System.Out.Println(obj.toString(2));
Try below code :-
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("key", "value");
String jsonString = jsonObject.toString();
I hope this will work for you.
I need to form a JSON object like this.
{
"GroupID": 24536,
"Section": [1,2,3,4,5]
}
Here is what i have tried, but the section array is not getting properly formed when i look at my object structure.
JSONObject Object = new JSONObject();
Object.put("Group", GroupID);
int[] section = {1,2,3,4,5};
Object.put("Section", section);
Try:
JSONObject Object = new JSONObject();
Object.put("Group", GroupID);
Integer[] section = {1,2,3,4,5};
Object.put("Section", new JSONArray(Arrays.asList(section)));
Try:
JSONObject Object = new JSONObject();
Object.put("Group", GroupID);
int[] section = {1,2,3,4,5};
JSONArray arr = new JSONArray();
arr.put(section);
Object.put("Section", arr);
Or create a Collection and set it as the value:
Collection c = Arrays.asList(section);
Object.put("Section", c);
You need to make use of JSONArray for inserting set of values that represent an array, in this case int array.
String strJson = null;
try{
int[] section = {1,2,3,4,5};
JSONObject jo = new JSONObject();
jo.put("GroupId", 24536);
JSONArray ja = new JSONArray();
for(int i : section)
ja.put(i);
jo.put("Section", ja);
strJson = jo.toString();
}
catch (Exception e) {
e.printStackTrace();
}
Now you've got json string inside strJson.