How do I remove the contents from a file? - java

How do I remove the content added to a file in append mode. This file contains large amount of records prior to the appended data.
How do I remove the jsonObject3 and jsonObject4 from this file? Please refer the code below
public class MainDemo {
public static void main(String[] args) throws SQLException,
ClassNotFoundException, IOException {
String FileSeparator=System.getProperty("file.separator");
Path p=Paths.get("Dummy\\Downloads\\Test\\2018-12-28\\D");
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("id",1);
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("id",2);
JSONObject jsonObject3 = new JSONObject();
jsonObject3.put("id",3);
JSONObject jsonObject4 = new JSONObject();
jsonObject4.put("id",4);
List<JSONObject> al=new ArrayList<>();
al.add(jsonObject1);
al.add(jsonObject2);
al.add(jsonObject3);
al.add(jsonObject4);
for(JSONObject jsonObject:al) {
String json=jsonObject.toString();
Files.write(
Paths.get(p+FileSeparator+"Dummy.json"),
json.getBytes(),
StandardOpenOption.APPEND);
}
al.clear();
// How do I remove the jsonObject3 and jsonObject4 from Dummy.json file
}
}

In this case you should append the objects with the help of a separator string or a symbol like '$' etc and then you can read the file and then store the read string in a string variable.
Then you will get the objects in an array using string.split(separatorString).
Then remove the element which you want and rewrite the data in the file in overwrite mode from the array.

Related

how to make json with same key different value in java

i'm trying to make a function
reading from specific directory and make a json file with that file's title in directory.
it reads file's title well but when i print out, it overlaps again and again
i need same key name and different value.
is there any way to put a number on key name or make same key?
bullet01.png
{"file":"bullet01.png"}
bullet011.png
{"file":"bullet011.png"}
bullet012.png
{"file":"bullet012.png"}
bullet013.png
{"file":"bullet013.png"}
bullet02.png
{"file":"bullet02.png"}
this is a full code
public void downloadFile(ViewMeta view) throws IOException {
DataSet input = view.getInputDataSet();
HttpServletRequest request = view.getHttpServletRequest();
String filePath = request.getServletContext().getRealPath("/curriculum1.4/filedir");
DataSet output = new DataSet();
File dir = new File(filePath);
String files[] = dir.list();
JSONObject data= new JSONObject();
for(String fn : files) {
System.out.println(fn);
data.put("file", fn);
System.out.println(data);
}
view.setAttribute("file", data);
view.printJSON();
}
this is a setAttribute structure
public void setAttribute(String key, Object val) {
if (this.keyList == null) {
this.keyList = new ArrayList();
}
this.keyList.add(key);
this.request.setAttribute(key, val);
this.request.setAttribute("coreframe.object.keyList", this.keyList);
}
if you want same key and have different value, you can make it as JSONArray format.
[{"file" : "bullet01.png"}, {"file" : "bullet02.png"}, {"file" : "bullet03.png"}]
your code may need to change like this :
.....
JSONArray array = new JSONArray();
for(String fn : files) {
//create json object for each file
JSONObject data= new JSONObject();
System.out.println(fn);
data.put("file", fn);
System.out.println(data);
//put json object into json array
array.put(data);
}
view.setAttribute("file", array);
view.printJSON();
No, the keys in the JSON should be unique. You can try appending numbers at the end of the key "file"

JSONObject from Google Maps parse in Java

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));
}

Access intended values in JSON file using JAVA

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.

JSON-Simple. Append to a JSONArray

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

How do I create a JSONObject?

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"}

Categories

Resources