I'm trying to "create" a JSONObject. Right now I'm using JSON-Simple and I'm trying to do something along the lines of this (sorry if any typo's are made in this example JSON file)
{
"valuedata": {
"period": 1,
"icon": "pretty"
}
}
Right now I'm having issues finding on how to write valuedata into a JSON file through Java, what I did try was:
Map<String, String> t = new HashMap<String, String>();
t.put("Testing", "testing");
JSONObject jsonObject = new JSONObject(t);
but that just did
{
"Testing": "testing"
}
Whatr you want to do is put another JSONObject inside your JSONObject "jsonObject", in the field "valuedata" to be more exact. You can do this like that...
// Create empty JSONObect here: "{}"
JSONObject jsonObject = new JSONObject();
// Create another empty JSONObect here: "{}"
JSONObject myValueData = new JSONObject();
// Now put the 2nd JSONObject into the field "valuedata" of the first:
// { "valuedata" : {} }
jsonObject.put("valuedata", myValueData);
// And now add all your fields for your 2nd JSONObject, for example period:
// { "valuedata" : { "period" : 1} }
myValueData.put("period", 1);
// etc.
Following is example which shows JSON object streaming using Java JSONObject:
import org.json.simple.JSONObject;
class JsonEncodeDemo
{
public static void main(String[] args)
{
JSONObject obj = new JSONObject();
obj.put("name","foo");
obj.put("num",new Integer(100));
obj.put("balance",new Double(1000.21));
obj.put("is_vip",new Boolean(true));
StringWriter out = new StringWriter();
obj.writeJSONString(out);
String jsonText = out.toString();
System.out.print(jsonText);
}
}
While compile and executing above program, this will produce following result:
{"balance": 1000.21, "num":100, "is_vip":true, "name":"foo"}
Related
I am kinda new to Rest assured testing, I have been dealing with diff. json and Api's.
I know how to pass a json object as body for POST request but my code gives error when I try to pass a JSON Array as body for POST request can someone suggest me how to do it.
The code I have been using for json object is
obj = parser.parse(new FileReader("path of json"));
jsonObject = (JSONObject) obj;
String jsonString = jsonObject.toJSONString();
Map<String, String> body = new ObjectMapper().readValue(jsonString, HashMap.class);
response = RestAssuredExtension.PostOpsWithBody(url, body);
This code gives class cast exception at
jsonObject = (JSONObject) obj; when I pass a json array.
Kindly help me with the same
This is the JSON Array
[
{
"findingId": "20177044",
"unsupressAfterDuration": 1669968369043,
"developer": "manan.girdhar#armorcode.io",
"kbIds": [],
"ticketConfigurationId": "3350",
"customFields": []
}
]
Your parser parses the part of JSON and probably returns a JSONArray, but you are casting it to JSONObject. Maybe you want to use something like
obj = parser.parse(new FileReader("path of json"));
if (obj instanceof JSONObject) {
jsonObject = (JSONObject) obj;
String jsonString = jsonObject.toJSONString();
Map<String, String> body = new ObjectMapper().readValue(jsonString, HashMap.class);
response = RestAssuredExtension.PostOpsWithBody(url, body);
} else {
throw new Exception("We do not know how to handle non-objects like " + obj.getClass().getName());
// replace this with list-handling code
}
If you want only one code fragment to handle both objects and lists, cast to JsonStructure.
answering my own question as I found a solution
JSONArray array1 = new JSONArray();
data1.put("findingId", findingIdFinal);
data1.put("unsupressAfterDuration", "1669968369043");
data1.put("developer","manan.girdhar#armorcode.io");
data1.put("kbIds",array1);
data1.put("ticketConfigurationId", jiraId);
data1.put("customFields",array1);
array.put(data1);
String jsonString = array.toString();
List<Map<String, String>> body = new ObjectMapper().readValue(jsonString, List.class);
response = RestAssuredExtension.PostOpsWithBodyWithArray(url, body);
This is the JSON file I am working with
{"sentiment":
{"document":
{
"label": "positive",
"score": 0.53777
}
}
}
I need to access the value in label and score. using java. How can I do that?
Find below the code I am using right now:
JSONParser parser = new JSONParser();
try
{
Object object = parser
.parse(new FileReader("output_nlu_sentiment.json"));
//convert Object to JSONObject
JSONObject jsonObject = new JSONObject();
JSONObject sentimentobject= new JSONObject();
JSONObject documentobject = new JSONObject();
sentimentobject= (JSONObject) jsonObject.get("sentiment");
documentobject= (JSONObject) sentimentobject.get("document");
String label = (String) documentobject.get("label");
//float score = (float) jsonObject.get("score");
System.out.println(label);
String test = (String) sentimentobject.get("label");
System.out.println(test);
} catch(FileNotFoundException fe)
{
fe.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
Why is it printing the value as null.
You might want to have a look at JacksonXml for json parsing.
Right now the problem is that you're not using the JsonObject returned by parser.parse(...).
Instead you use the get method on objects you just created. This of course means that you don't getthe valie you want to.
Try to use following code (JSONObject jsonObject = (JSONObject) object instead of JSONObject jsonObject = new JSONObject();), because you didn't use object at all, just create new empty JSONObject.
JSONParser parser = new JSONParser();
try
{
Object object = parser
.parse(new FileReader("output_nlu_sentiment.json"));
//convert Object to JSONObject
JSONObject jsonObject = (JSONObject) object;
JSONObject sentimentobject = (JSONObject) jsonObject.get("sentiment");
JSONObject documentobject= (JSONObject) sentimentobject.get("document");
String label = (String) documentobject.get("label");
System.out.println(label);
float score = (float) documentobject.get("score");
System.out.println(score );
}catch(FileNotFoundException fe)
{
fe.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
You have to make use of object created in Object object = parser.parse(new FileReader("output_nlu_sentiment.json")); while creating the jsonObject
For that you can look at the code below:
Object object = parser
.parse(new FileReader("file2.json"));
//convert Object to JSONObject
JSONObject jsonObject = (JSONObject) object;
JSONObject sentimentobject= new JSONObject();
JSONObject documentobject = new JSONObject();
sentimentobject= (JSONObject) jsonObject.get("sentiment");
documentobject= (JSONObject) sentimentobject.get("document");
String label = (String) documentobject.get("label");
//float score = (float) jsonObject.get("score");
System.out.println(label);
String test = (String) sentimentobject.get("label");
You will get the positive printed on console.
you should see the content in para 'sentimentobject',force convert into class JSONObject can not get the value you want.
I prefer the FasterXML Jackson support to parse JSON into plain old Java objects (POJOs). These POJOs are often called Data Transfer Objects (DTOs) and give you a way to turn your JSON fields into properly typed members of the corresponding DTO.
Here is an example method to do that. The ObjectMapper(s) are generally maintained as statics somewhere else because FasterXML's implementation caches information to improve efficiency of object mapping operations.
static final ObjectMapper mapper = new ObjectMapper();
This is the JSON deserialization method:
public static <T> T deserializeJSON(
final ObjectMapper mapper, final InputStream json,
final Class<T> clazz)
throws JsonParseException, UnrecognizedPropertyException,
JsonMappingException, IOException
{
final String sourceMethod = "deserializeJSON";
logger.entering(sourceClass, sourceMethod);
/*
* Use Jackson support to map the JSON into a POJO for us to process.
*/
T pojoClazz;
pojoClazz = mapper.readValue(json, clazz);
logger.exiting(sourceClass, sourceMethod);
return pojoClazz;
}
Assuming I have a class called FooDTO, which has the appropriate Jackson annotations/getters/setters (note you must always provide a default empty public constructor), you can do this:
FooDTO foo = deserializeJSON(mapper, inputstream, FooDTO.class);
The deserialization throws a few different exceptions (all of which have IOException as their parent class) that you will need to handle or throw back to the caller.
Here besides of the correction alreay addressed in comments and other answers, I include some other changes you can benefit of:
It is not necessary to initialize the JSONObjects with a new instance that is going to be ovewritten in the next line.
You can use getJSONObject(), getString(), getFloat() instead of get(), in this way you don't need to cast the result.
public void parseJson() {
JSONParser parser = new JSONParser();
try
{
JSONObject jsonObject = new JSONParser().parse(new FileReader("output_nlu_sentiment.json"));
JSONObject sentimentobject= null;
JSONObject documentobject = null;
sentimentobject= jsonObject.getJSONObject("sentiment");
documentobject= sentimentobject.getJSONObject("document");
String label = documentobject.getString("label");
float score = documentobject.getFloat("score");
String output = String.format("Label: %s Score: %f", label, score);
System.out.println(output);
}catch(FileNotFoundException fe){
fe.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}
Also for this kind of objects, where the attribute names could act as object properties, I suggest you take a look at Gson library. After modeling the json as a composition of POJOs, the parsing takes 1 line of code.
My JSON Structure will vary depend on the request. But the content inside each element remain same. For Example:
JSON1:
{
"h1": {
"s1":"s2"
},
"c1": {
"t1:""t2"
}
}
JSON2:
{
"h1": {
"s1":"s2"
},
"c2": {
"x1:""x2"
}
}
In the above example, elements inside h1,c1 and c2 are constant. Please let me know how to convert JSON to JAVA Object
Regards
Udhaya
First of all You need to understand Json Structure cause above format is incorrect visit this
and this
And you can use Google Gson or Json for parsing the result json String .
"t1:""t2" json format incorrect
Used
"t1":"t2"
Instead of
"t1:""t2"
and also used
"x1": "x2"
Instead of
"x1:""X2"
Code to take in java
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject jsonsubObject = jsonObject.getJSONObject("h1");
String s1 = jsonsubObject.getString("s2");
JSONObject jsonsubObject1 = jsonObject.getJSONObject("c1");
String t1 = jsonsubObject1 .getString("t2");
}
catch (JSONException e) {
e.printStackTrace();
}
Use Google Gson:
Gson gson = new Gson();
ClassName object;
try {
object = gson.fromJson(json, ClassName.class);
} catch (com.google.gson.JsonSyntaxException ex) {
//the json wasn't valid json
}
String validJson = gson.toJson(obj); //obj is an instance of any class
json must be a valid JSON String
import org.json.JSONObject;
you can simple pass your data in constructor of JSONObject it automatically handle, you need to throws JSONException which may occur during conversion id format of data is not correct
String data = "{'h1':{'s1':'s2'},'c1':{'t1:''t2'}}";
JSONObject jsnobject = new JSONObject(data);
I am using the JSON-simple library to parse the Json format. How can I append something to a JSONArray? For e.g. consider the following json
{
"a": "b"
"features": [{/*some complex object*/}, {/*some complex object*/}]
}
I need to append a new entry in the features.
I am trying to create a function like this:-
public void appendToList(JSONObject jsonObj, JSONObject toBeAppended){
JSONArray arr = (JSONArray)jsonObj.get("features");
//1) append the new feature
//2) update the jsonObj
}
How to achieve steps 1 & 2 in the above code?
You can try this:
public static void main(String[] args) throws ParseException {
String jsonString = "{\"a\": \"b\",\"features\": [{\"feature1\": \"value1\"}, {\"feature2\": \"value2\"}]}";
JSONParser parser = new JSONParser();
JSONObject jsonObj = (JSONObject) parser.parse(jsonString);
JSONObject newJSON = new JSONObject();
newJSON.put("feature3", "value3");
appendToList(jsonObj, newJSON);
System.out.println(jsonObj);
}
private static void appendToList(JSONObject jsonObj, JSONObject toBeAppended) {
JSONArray arr = (JSONArray) jsonObj.get("features");
arr.add(toBeAppended);
}
This will fulfill your both requirements.
Getting the array by: jsonObj["features"], then you can add new item by assign it as the last element in the array ( jsonObj["features"].length is the next free place to add new element)
jsonObj["features"][jsonObj["features"].length] = toBeAppended;
fiddle example
I am trying to create an image view from json url. I am getting the url using a for-loop in a string. I could not use that variable outside the for-loop. I tried constructing an arraylist inside the for-loop. This is what I am getting in the log.
Creating view...[[], [], [], [], [], [], [], [], [], []]
Here is my code.
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
// Log.v("url", "Creating view..." + json);
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG_URL);
for (int i = 0; i < android.length(); i++) {
map = new ArrayList<HashMap<String, String>>();
JSONObject c = android.getJSONObject(i);
String name = c.getString(TAG_URL);
arraylist.add(map);
// Log.v("url", name);
}
Log.v("url", "Creating view..." + arraylist);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
Here is the json:
http://www.json-generator.com/api/json/get/ciCLARKtKa?indent=4
When in doubt on how to create a POJO from a JSON, I'd recommend you to try this site:
http://www.jsonschema2pojo.org/
It outputs you a full java class that works for a given json type;
For most cases I'd recommend you to use this config (from the website above):
Source type: Json
Annotation style: None
And check ONLY use primitives.
Hope it helps !
hi do something as follows
JSONObject primaryObject = new JSONObject(//yours json string);
JSONArray primaryArray = primaryObject.getJSONArray("worldpopulation");
for (int i = 0; i < primaryArray.length(); i++) {
JSONObject another = primaryArray.getJSONObject(i);
String country = another.getString("country");
String flag = another.getString("flag");
int rank = another.getInt("rank");
String population = another.getString("population");
HashMap<String, String> map = new HashMap<String, String>();
map.put("flag", flag);
arraylist.add(i, map);
}
I think you missed put the values into MAP.
Try use like this
for (int i = 0; i < android.length(); i++) {
JSONObject c = android.getJSONObject(i);
// Storing each json item in variable
String flag = c.getString("flag");
HashMap<String, String> map = new HashMap<String, String>();
map.put("flag", flag);
arraylist.add(i, map);
}