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
Related
I'm trying to get a nested array from a json file, but I can't find a way to do it. What I want is a array with many other arrays. Using arr.toArray() I get a array with two strings one being "["user1", "name", "password"]" and "["user2", "name", "password"]". Is there a way to get an array with arrays?
{
"Users": {
"info": [
["user1", "name", "password"],
["user2", "name", "password"]
]
}
}
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("myPath"));
JSONObject jsonObject = (JSONObject) obj;
JSONObject jsonObject1 = (JSONObject) jsonObject.get("User1");
JSONArray arr = (JSONArray) jsonObject1.get("info");
System.out.println(arr.toArray());
} catch (Exception e) {
e.printStackTrace();
}
}
I think you might be using one of the older JSON Libraries, I believe its the org.json.simple library. If this is going to be an important project, I'd recommend switching over to the Google GSON Library.
For now, Try Switching
JSONObject jsonObject1 = (JSONObject) jsonObject.get("User1");
to
JSONObject jsonObject1 = (JSONObject) jsonObject.get("Users");
this should fix some of your problems. In your JSON file, Users is the object you need to get in order to access the info Array.
in the mean time, here's a starting place for GSON
GSON tutorialspoint
https://www.tutorialspoint.com/gson/gson_quick_guide.htm
I'm trying to parse Java Object to get data from a URL. I'm using getJSONObject and getString methods from org.json.JSONObject library but this it's not working. I'm doing something like...
JSONObject jsonCoord = json.getJSONObject("results")
.getJSONObject("geometry")
.getJSONObject("location");
coordinates[0] = jsonCoord.getString("lat");
coordinates[1] = jsonCoord.getString("lng");
JSON document I want to parse (Part 1)
JSON document I want to parse (Part 2)
How can I get "lat" and "lng" which is inside of "geometry"?
Here it is:
public static void main(String args[]) throws Exception {
String content = new String(Files.readAllBytes(Paths.get("test.json")), "UTF-8");
JSONObject json = new JSONObject(content);
JSONArray results = json.getJSONArray("results");
JSONObject result = (JSONObject) results.get(0); //or iterate if you need for each
JSONObject jsonCoord = result.getJSONObject("geometry").getJSONObject("location");
System.out.println(jsonCoord);
String[] coordinates = new String[2];
coordinates [0] = jsonCoord.getString("lat");
coordinates[1] = jsonCoord.getString("lng");
System.out.println(Arrays.asList(coordinates));
}
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.
I have String "[{...}]" and I want convert it to JSONArray, and then to List list = new List I was trying this solution, and this is my code
public void RestoreData()
{
String toConvert = "[{...}]" // I don't place full String, but it's typical JSONArray, but in String
ArrayList<myClass> listdata = new ArrayList<myClass>();
JsonObject jsonObject = new JsonObject();
JSONArray jArray = (JSONArray)jsonObject;
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
listdata.add(jArray.getString(i));
}
}
}
And when I'm trying to compile this I get 2 errors:
In JSONArray jArray = (JSONArray)jsonObject; I get error 'Incovertible types; cannot cast 'org.json.JSONObject' to 'org.json.JSONArray'.
And second: in listdata.add(jArray.getString(i)); I get error 'unhandled exception org.json.JSONException'.
I'm new in Java and I work with Json for the first time.
EDIT
A small truncated example of the Json string:
[{"lootArmorGain":0,"lootBlockGain":0,"lootCost":93500,"lootCritGain":2,"lootCritPowerGain":0,"lootDamageAbsorptionGain":0,"lootDamageGain":0,
}]
I think what you want is:
public void RestoreData()
{
try{
String toConvert = "[{...}]" // I don't place full String, but it's typical JSONArray, but in String
ArrayList<MyClass> listdata = new ArrayList<MyClass>();
JSONArray jsonArray = new JSONArray(toConvert);
if (jsonArray != null) {
Gson gson = new Gson();
for (int i=0;i<jsonArray.length();i++){
String json = jsonArray.getJSONObject(i).toString();
MyClass obj = gson.fromJson(json, MyClass.class);
listdata.add(obj);
}
}
}catch(JSONException e){
e.printStackTrace();
}
}
To convert from JSONOject to your custom class use GSON, see above.
compile 'com.google.code.gson:gson:2.8.4'
Note that your custom class need to have an empty constructor as well as getters and setters in order to make gson work.
I think best approach will be using Google Gson Library.
String toConvert = "[{...}]"
Type listType = new TypeToken<List<myClass>>() {}.getType();
List<myClass> yourList = new Gson().fromJson(toConvert, listType);
You dont need to get each position manually.
For simplicity you can also use Jackson api
ObjectMapper objectMapper = new ObjectMapper();
TypeFactory typeFactory = objectMapper.getTypeFactory();
List<SomeClass> someClassList = objectMapper.readValue(jsonString,typeFactory.constructCollectionType(List.class, SomeClass.class));
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"}