how to make json with same key different value in java - 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"

Related

How do I remove the contents from a file?

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.

How the value of HashMap changes?

I parse some xml files using XStream libraries. The result is a map for every file. When I debug, the result map is what I was looking for, but when I go to next line the value of map changes out of the blue! However it doesn't go for the next round in the "for" loop, it contains the information of next file. What can cause it?
public class Debug {
public String path = "E:\\Projects\\svn\\FANRPProduction\\WMS\\src\\main\\resources\\wms\\bpmn\\bp";
public XStream xStream;
public Map<String, List<CallActivity>> bpTpMap;
public void findBPandTP() throws IOException {
File root = new File(path);
File[] xmlFiles = FindAllXMLFiles.recursive(root);
bpTpMap=new HashMap<String, List<CallActivity>>();
for (File xml : xmlFiles) {
if (xml != null) {
xStream = new XStream(new StaxDriver());
xStream.alias("definitions", CallActivity.class);
xStream.registerConverter(new CallActivityConverter());
bpTpMap = (Map) xStream.fromXML(xml);//Here I get correct information. For example "WMS_RBP_OutgoingWeighing"
List<String> bpList = new ArrayList<String>(bpTpMap.keySet()); //Here I see the name of the next file in the path in bpTpMap, which is "WMS_BP_WeighingConfiguration"
}
}
}
}
I would suggest you to debug with the following:
bpTpMap = (Map) xStream.fromXML(xml);//Here I get correct information. For example "WMS_RBP_OutgoingWeighing"
System.out.println(bpTpMap.size());
Set<String> setOfKeys = bpTpMap.keySet();
System.out.println("Initial value of keys:"+bpTpMap);//Here you would see any extra values if the map has it

How to add List into properties file?

I am converting properties file into xml format like below .
public class XmlPropertiesWriter {
public static void main(String args[]) throws FileNotFoundException, IOException {
//Reading properties files in Java example
Properties props = new Properties();
FileOutputStream fos = new FileOutputStream("C:\\Users\\Desktop\\myxml.xml");
props.setProperty("key1", "test");
props.setProperty("key2", "test1");
//writing properites into properties file from Java
props.storeToXML(fos, "Properties file in xml format generated from Java program");
fos.close();
}
}
This is working fine.But I want to add one ArrayList into this xml file,How can I do this,Any one help me.
You can (un)serialized the list into string representation to store the data into the properties file:
ArrayList<String> list = new ArrayList<>( );
String serialized = list.stream( ).collect( Collectors.joining( "," ) );
String input = "data,data"
List<String> unserialized = Arrays.asList( input.split( "," ) );
With this method, take care to use a seperator which is never contained in your data.
Otherwise, write a xml (or json) file reader/writer to do what you want with support of list element
Depends on what type the ArrayList is. If it's a String type you can do
arrayList.toArray(new String[arrayList.size()]);
If the type is an object you can create a StringBuilder and add all the values seperated by a ; or : so you can split when needed
final StringBuilder builder = new Stringbuilder();
final List<Point> list = new ArrayList<Point>();
list.add(new Point(0, 0));
list.add(new Point(1, 0));
for(final Point p : list) {
builder.append(p.toString()).append(";");
}
properties.setProperty("list", builder.toString());
When you load the properties you can simply do then
final List<Point> list = new ArrayList<Point>();
final String[] points = properties.getProperty("list").split(";");
for(final String p : points) {
final int x = Integer.parseInt(p.substring(0, p.indexOf(","));
final int y = Integer.parseInt(p.substring(p.indexOf(","), p.indexOf(")"));
list.add(new Point(x, y);
}

Java: Append Value to Property Key

I am using java.util.Properties to store properties in a file. I am able to store key/value pair successfully using the following code:
public String setKeyValue(String dir, String key, String value) throws FileNotFoundException, IOException
{
File file = new File(dir);
FileInputStream in = new FileInputStream(file);
Properties properties = new Properties();
properties.load(in);
in.close();
FileOutputStream out = new FileOutputStream(file);
properties.setProperty(key, value);
properties.store(out, null);
out.close();
String myValue = (String) properties.getProperty(key);
System.out.println (myValue);
return myValue;
}
However, I am interested in updating (not replacing) a previous property so I can later retrieve them as an array.
For example my current property looks something like this:
email=email1
I want to change it to
email=email1, email2 //(this will be a continuous process of adding more emails)
This way I can later retrieve them as follows:
String[] emailList = properties.getProperty("email").split(",");
If you use the previous code it simply replaces the property. I need to append additional "value" to key..
Well, the most simple way would be do this...
String oldValue = properties.getProperty( key );
String newValue = "bla something";
String toStore = oldValue != null ? oldValue + "," + newValue : newValue;
properties.setProperty( key, value );
Of course, that's not very elegant, so I personally would probably extend my own AppenderProperties class from Properties and then add an append method. This would also be a good place to put all the array-related methods, so that you can remove specific values from your keys, etc.

Convert String in JSON format into CSV / List of Strings

I have created an CSV exporter where I am converting String in JSON format into the Collection of objects and then into the List of strings.
Gson gson = new Gson();
Type collectionType = new TypeToken<Collection<itemModel>>(){}.getType();
Collection<itemModel> objects = gson.fromJson(jsonString, collectionType);
// jsonString = "[{"name":"A","number":25},{"name":"B","number":26}]"
String filename = "export.csv";
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
ec.responseReset();
ec.setResponseContentType("text/comma-separated-values");
ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
OutputStream output = ec.getResponseOutputStream();
List<String> strings = new ArrayList<String>();
for (itemModel obj : objects) {
strings.add(obj.getName() + ";" + obj.getNumber() +"\n");
}
for (String s : strings) {
output.write(s.getBytes());
}
fc.responseComplete();
Now, I would like to do the adding of a new string into the List dynamically and replace this row: strings.add(obj.getName() + ";" + obj.getNumber() +"\n"); It should be more robust. Is somehow possible call all getters if I dont know exact names of properties?
Or is better solution how to convert String in JSON format into the List of strings?
Any advice would be appreciated!
You need to override toString() method in itemModel Class and build your string according to CSV foramt
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(name);
builder.append(";");
builder.append(number);
builder.append("\n");
return builder.toString();
}
// finally wrtie
List<itemModel> itemModels = gson.fromJson(jsonString, collectionType);
for (itemModel itemModel : itemModels) {
output.write(itemModel.toString().getBytes());
}
Implementing toString() of ItemModel is good if you already know all the properties.
You can use Reflection to get all the properties if you already don't know them.

Categories

Resources