I want the following json ,where List<form> will have list of form_id,form_name, how can I convert this using jsonobject, I am not getting the proper json output. Please help me with this.
Json:
{
"forms": [
{ "form_id": "1", "form_name": "test1" },
{ "form_id": "2", "form_name": "test2" }
]
}
The above is the json structure that i need it for a list.Where id ,name is a list from form object
public static JSONObject getJsonFromMyFormObject(List<Form> form) {
JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = null;
System.out.println(form.size());
for (int i = 0; i < form.size(); i++) {
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("form_id", form.get(i).getId());
formDetailsJson.put("form_name", form.get(i).getName());
jsonArray = new JSONArray();
jsonArray.add(formDetailsJson);
}
responseDetailsJson.put("form", jsonArray);
return responseDetailsJson;
}
Facing issue here not getting output as a list
The code in the original question is close to achieving the described desired result. Just move the JSONArray instance creation outside of the loop.
import java.util.ArrayList;
import java.util.List;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class Foo
{
public static JSONObject getJsonFromMyFormObject(List<Form> form)
{
JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < form.size(); i++)
{
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("form_id", form.get(i).getId());
formDetailsJson.put("form_name", form.get(i).getName());
jsonArray.add(formDetailsJson);
}
responseDetailsJson.put("forms", jsonArray);
return responseDetailsJson;
}
public static void main(String[] args)
{
List<Form> forms = new ArrayList<Form>();
forms.add(new Form("1", "test1"));
forms.add(new Form("2", "test2"));
JSONObject jsonObject = getJsonFromMyFormObject(forms);
System.out.println(jsonObject);
}
}
class Form
{
String id;
String name;
Form(String i, String n)
{
id = i;
name = n;
}
String getId()
{
return id;
}
String getName()
{
return name;
}
}
Properbly http://www.roseindia.net/tutorials/json/jsonobject-java-example.shtml will help.
According the comment from Tushar, here the extract from the aboved linked website:
Now in this part you will study how to use JSON in Java.
To have functionality of JSON in java you must have JSON-lib. JSON-lib also
requires following "JAR" files:
commons-lang.jar
commons-beanutils.jar
commons-collections.jar
commons-logging.jar
ezmorph.jar
json-lib-2.2.2-jdk15.jar
JSON-lib is a java library for that transforms beans, collections, maps, java arrays and XML to JSON and
then for retransforming them back to beans, collections, maps and
others. In this example we are going to use JSONObject class for
creating an object of JSONObject and then we will print these object
value. For using JSONObject class we have to import following package
"net.sf.json". To add elements in this object we have used put()
method. Here is the full example code of FirstJSONJava.java is as
follows:
FirstJSONJava.java
import net.sf.json.JSONObject;
public class FirstJSONJava
{
public static void main(String args[])
{
JSONObject object=new JSONObject();
object.put("name","Amit Kumar");
object.put("Max.Marks",new Integer(100));
object.put("Min.Marks",new Double(40));
object.put("Scored",new Double(66.67));
object.put("nickname","Amit");
System.out.println(object);
}
}
To run this example you have to follow these few steps as follows:
Download JSON-lib jar and other supporting Jars
Add these jars to your classpath
Create and save FirstJSONJava.java
Compile it and execute it.
Related
I have this json:
{
"sid": "BiQo7DA4lMoRkeGN8mdfBXackyBarCSSauQtNRRKOmcfo2Ah0XCjaI1yevEoxWa09TkTOYrwGixRMvBr15h1d2",
"submissions": [{
"submission_id": "1104764"
}, {
"submission_id": "1104765"
}]
}
How can I in AndroidStudio get a list of items by submission_id?(there is always 30 items in "submissions")
Thanks
UPDATED
I'm trying with this code but show exception.
for (int i = 0; i < jObject.length(); i++) {
JSONObject subm = jObject.getJSONObject("submissions");
JSONObject jObj = subm.getJSONObject(String.valueOf(i));
testdata = testdata + " " + jObject.getString("submission_id");
//
}
I basically want to get all the elements inside the "submissions"...
Path : POJO classes -> GSON -> list
You can use Google GSON to read JSON into Java objects.
POJO
public class Submission
{
public String submission_id;
public Submission(String submission_id)
{
this.submission_id = submission_id;
}
}
public class SubmissionObject
{
public String sid;
public List<Submission> submissions;
public SubmissionObject(String sid,List<Submission> submissions)
{
this.sid = sid;
this.submissions = submissions;
}
}
POJOs are ready. Let's parse the JSON response by using GSON.
public List<Submission> submissions = new ArrayList<>();//your list holds the all submissions.
Gson gson = new Gson();// initialize GSON parser
SubmissionObject object = gson.fromJson(jsonResponse.toString(), SubmissionObject.class); //get the object
submissions = object.submissions; // set list
Try this one:
if (!jObject.isNull("submissions")) {
JSONArray submissions = jObject.getJSONArray("submissions");
for(int i = 0; i < submissions.length(); i++) {
JSONObject submission = submissions.getJSONObject(i);
String submissionId = submission.getString("submission_id");
}
}
I have the following JSON Array as a string like this,
String output = "[{\"Symbol\":\"AMZN\",\"Name\":\"Amazon.com Inc\",\"Exchange\":\"NASDAQ\"},{\"Symbol\":\"VXAZN\",\"Name\":\"CBOE Amazon VIX Index\",\"Exchange\":\"Market Data Express\"}]";
I want to parse it and make a string array like this,
array = {"AMZN Amazon.com Inc NASDAQ", "VXAZN CBOE Amazon VIX Index Market Data Express"};
I came up with the following code to parse the string into a JSON Array using the json-simple-1.1.1.jar library,
import org.json.simple.*;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class RESTclient {
public static void main(String[] args) {
String output = "[{\"Symbol\":\"AMZN\",\"Name\":\"Amazon.com Inc\",\"Exchange\":\"NASDAQ\"},{\"Symbol\":\"VXAZN\",\"Name\":\"CBOE Amazon VIX Index\",\"Exchange\":\"Market Data Express\"}]";
JSONParser parser = new JSONParser();
JSONArray jsonArray = null;
try {
jsonArray = (JSONArray) parser.parse(output);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(jsonArray);
}
}
This gives me the following OUTPUT,
[{"Name":"Amazon.com Inc","Exchange":"NASDAQ","Symbol":"AMZN"},{"Name":"CBOE Amazon VIX Index","Exchange":"Market Data Express","Symbol":"VXAZN"}]
Now after this, is there an elegant way to achieve my desired output?
You have to write extra code.
ArrayList<String> stringArray = new ArrayList<String>();
for (Iterator iterator = jsonArray.iterator(); iterator.hasNext();) {
JSONObject map = (JSONObject)iterator.next();
stringArray.add(map.get("Symbol")+" "+map.get("Name")+" "+map.get("Exchange"));
}
//stringArray is want you want
You can do it with Jackson like,
private ObjectMapper mapper = new ObjectMapper();
String[] outputArray = mapper.readValue(jsonString, String[].class);
I am coding a feature in which I read and write back json. However I can read the json elements from a file but can't edit the same loaded object. Here is my code which I am working on.
InputStream inp = new FileInputStream(jsonFilePath);
JsonReader reader = Json.createReader(inp);
JsonArray employeesArr = reader.readArray();
for (int i = 0; i < 2; i++) {
JsonObject jObj = employeesArr.getJsonObject(i);
JsonObject teammanager = jObj.getJsonObject("manager");
Employee manager = new Employee();
manager.name = teammanager.getString("name");
manager.emailAddress = teammanager.getString("email");
System.out.println("uploading File " + listOfFiles[i].getName());
File file = insertFile(...);
JsonObject tmpJsonValue = Json.createObjectBuilder()
.add("fileId", file.getId())
.add("alternativeLink", file.getAlternateLink())
.build();
jObj.put("alternativeLink", tmpJsonValue.get("alternativeLink")); <-- fails here
}
I get the following exception when I run it.
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractMap.put(AbstractMap.java:203)
at com.mongodb.okr.DriveQuickstart.uploadAllFiles(DriveQuickstart.java:196)
at com.mongodb.okr.App.main(App.java:28)
The javadoc of JsonObject states
JsonObject class represents an immutable JSON object value (an
unordered collection of zero or more name/value pairs). It also
provides unmodifiable map view to the JSON object name/value mappings.
You can't modify these objects.
You'll need to create a copy. There doesn't seem to be a direct way to do that. It looks like you'll need to use Json.createObjectBuilder() and build it yourself (see the example in the javadoc linked).
As answered by Sotirios, you can use JsonObjectBuilders.
To insert value into JsonObject, you can use method:
private JsonObject insertValue(JsonObject source, String key, String value) {
JsonObjectBuilder builder = Json.createObjectBuilder();
builder.add(key, value);
source.entrySet().
forEach(e -> builder.add(e.getKey(), e.getValue()));
return builder.build();
}
To insert JsonObject into JsonObject, you can use method:
private JsonObject insertObject(JsonObject parent, JsonObject child, String childName) {
JsonObjectBuilder child_builder = Json.createObjectBuilder();
JsonObjectBuilder parent_builder = Json.createObjectBuilder();
parent.entrySet().
forEach(e -> parent_builder.add(e.getKey(), e.getValue()));
child.entrySet().
forEach(e -> child_builder.add(e.getKey(), e.getValue()));
parent_builder.add(childName, child_builder);
return parent_builder.build();
}
Please note, if you change the child JsonObject after inserting it into another "parent" JsonObject, it will have no effect on the "parent" JsonObject.
JsonObject is immutable so you cannot modify the object , you can use this example and try to inspire from it : creation of a new JsonObject who contains the same values and add some elements to it ..
Example :
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonReader;
import javax.json.JsonValue;
public class Jsonizer {
public static void main(String[] args) {
try {
String s = "{\"persons\": [ {\"name\":\"oussama\",\"age\":\"30\"}, {\"name\":\"amine\",\"age\":\"25\"} ]}";
InputStream is = new ByteArrayInputStream(s.getBytes());
JsonReader jr = Json.createReader(is);
JsonObject jo = jr.readObject();
System.out.println("Before :");
System.out.println(jo);
JsonArray ja = jo.getJsonArray("persons");
InputStream targetStream = new ByteArrayInputStream("{\"name\":\"sami\",\"age\":\"50\"}".getBytes());
jr = Json.createReader(targetStream);
JsonObject newJo = jr.readObject();
JsonArrayBuilder jsonArraybuilder = Json.createArrayBuilder();
jsonArraybuilder.add(newJo);
for (JsonValue jValue : ja) {
jsonArraybuilder.add(jValue);
}
ja = jsonArraybuilder.build();
JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder();
jsonObjectBuilder.add("persons", ja);
JsonObject jsonAfterAdd = jsonObjectBuilder.build();
System.out.println("After");
System.out.println(jsonAfterAdd.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Output :
Before :
{"persons":[{"name":"oussama","age":"30"},{"name":"amine","age":"25"}]}
After
{"persons":[{"name":"sami","age":"50"},{"name":"oussama","age":"30"},{"name":"amine","age":"25"}]}
Try using the simple JSONObject, not javax.
import org.json.JSONObject;
You can download the jar or include it in your maven or gradle like so:
dependencies {
compile group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1.1'
}
also see:
creating json string using JSONObject and JSONArray
I created a simple POJO:
public class LoginPojo {
private String login_request = null;
private String email = null;
private String password = null;
// getters, setters
}
After some searching I found this: JSONObject jsonObj = new JSONObject( loginPojo );
But with this I got the error:
The constructor JSONObject(LoginPojo) is undefined
I found another solution:
JSONObject loginJson = new JSONObject();
loginJson.append(loginPojo);
But this method does not exist.
So how can I convert my POJO into a JSON?
Simply use the java Gson API:
Gson gson = new GsonBuilder().create();
String json = gson.toJson(obj);// obj is your object
And then you can create a JSONObject from this json String, like this:
JSONObject jsonObj = new JSONObject(json);
Take a look at Gson user guide and this SIMPLE GSON EXAMPLE for more information.
It is possible to get a (gson) JsonObject from POJO:
JsonElement element = gson.toJsonTree(userNested);
JsonObject object = element.getAsJsonObject();
After that you can take object.entrySet() and look up all the tree.
It is the only absolutely free way in GSON to set dynamically what fields you want to see.
Jackson provides JSON parser/JSON generator as foundational building block; and adds a powerful Databinder (JSON<->POJO) and Tree Model as optional add-on blocks. This means that you can read and write JSON either as stream of tokens (Streaming API), as Plain Old Java Objects (POJOs, databind) or as Trees (Tree Model). for more reference
You have to add jackson-core-asl-x.x.x.jar, jackson-mapper-asl-x.x.x.jar libraries to configure Jackson in your project.
Modified Code :
LoginPojo loginPojo = new LoginPojo();
ObjectMapper mapper = new ObjectMapper();
try {
mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY);
// Setting values to POJO
loginPojo.setEmail("a#a.com");
loginPojo.setLogin_request("abc");
loginPojo.setPassword("abc");
// Convert user object to json string
String jsonString = mapper.writeValueAsString(loginPojo);
// Display to console
System.out.println(jsonString);
} catch (JsonGenerationException e){
e.printStackTrace();
} catch (JsonMappingException e){
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
Output :
{"login_request":"abc","email":"a#a.com","password":"abc"}
JSONObject input = new JSONObject(pojo);
This worked with latest version.
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180130</version>
</dependency>
You can also use project lombok with Gson overriding toString function. It automatically includes builders, getters and setters in order to ease the data assignment like this:
User user = User.builder().username("test").password("test").build();
Find below the example class:
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import com.google.gson.Gson;
#Data
#Builder(toBuilder = true)
#AllArgsConstructor
#NoArgsConstructor
public class User {
/* User name. */
private String username;
/* Password. */
private String password;
#Override
public String toString() {
return new Gson().toJson(this, User.class);
}
public static User fromJSON(String json) {
return new Gson().fromJson(json, User.class);
}
}
Simply you can use the below solution:
ObjectMapper mapper = new ObjectMapper();
String str = mapper.writeValueAsString(loginPojo);
JSONObject jsonObject = new JSONObject(str);
I use jackson in my project, but I think that u need a empty constructor.
public LoginPojo(){
}
You can use
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.13</version>
</dependency>
To create a JSON object:
#Test
public void whenGenerateJson_thanGenerationCorrect() throws ParseException {
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < 2; i++) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("AGE", 10);
jsonObject.put("FULL NAME", "Doe " + i);
jsonObject.put("DATE OF BIRTH", "2016/12/12 12:12:12");
jsonArray.add(jsonObject);
}
String jsonOutput = jsonArray.toJSONString();
}
Add the annotations to your POJO class like so:
#JSONField(name = "DATE OF BIRTH")
private String dateOfBirth;
etc...
Then you can simply use:
#Test
public void whenJson_thanConvertToObjectCorrect() {
Person person = new Person(20, "John", "Doe", new Date());
String jsonObject = JSON.toJSONString(person);
Person newPerson = JSON.parseObject(jsonObject, Person.class);
assertEquals(newPerson.getAge(), 0); // if we set serialize to false
assertEquals(newPerson.getFullName(), listOfPersons.get(0).getFullName());
}
You can find a more complete tutorial on the following site:
https://www.baeldung.com/fastjson
I have a problem at hand..
public class SomeClass{
List<Template> templateSettings;
}
public class Template{
String id;
List<TemplateChild> child;
}
public class TemplateChild{
String id;
String something;
}
at the ajax level i have
#ajax
public class saveSettings(SomeClass someclass){
List<Template> templateSettings = someclass.getTemplateSettings();
}
Its a bit complex , can someone help me in constructing the JSON for this, i am very new to javascript.. thanks..
Gson library will do that for you, Its pretty simple to use, here is the link
You can simply download the jar file and create the object like this
{ Gson gson = new Gson();
String convertedJson = gson.toJson(yourobject);}
And you are done.
Your JSON should look like
templetSettings= [{
template = {id="someId", childs=[{id="someId", something="something"},{id="someId2", something="something2"}]}},{
template = {//same as above},{
template = {//same as above}
]
Use JSONObject and JSONArray to create this kind of structure. Its pretty easy to use really
JSONArray templateSettings = new JSONArray();
for(//configure loop accordigly) {
JSONObject template = new JSONObject();
JSONArray childs = new JSONArray();
for (//Configure accordingly) {
JSONObject child = new JSONObject;
child.put("id", "someId");
child.put("something", "something");
childs.add(child);
}
template.put("id", "someId");
template.put("childs", childs);
templateSettings.add(template);
}
After this you only need to do is
out.write(templateSettings.toString());
And you are done
To do this on javaScript side loop accordingly and take help from this example
http://jsfiddle.net/AMISingh/636vN/