I have this data in my text file.
Obj1= {
"AA" : "sasa",
"BB" : "fdsfsf",
"CC" : "sfsdf",
"DD" : "kmdksmd",
"EE" : "dsnjsdn"
};
Obj2= {
"DD" : "ndjsdnsjd",
"MM" : "jskdjskadn"
};
This data is in a single text file. How do I convert this to two different objects in JAVA
Is it possible to use more friendly, fully JSON format instead? It might look like:
{
"Obj1" : {
"AA" : "sasa",
"BB" : "fdsfsf",
"CC" : "sfsdf",
"DD" : "kmdksmd",
"EE" : "dsnjsdn"
},
"Obj2" : {
"DD" : "ndjsdnsjd",
"MM" : "jskdjskadn"
}
}
Then it would be very easy to load it like described in this thread
The file from your example isn't the correct JSON file so you can't do that so easily. If you really want to stick with your format, you would have to somehow tokenize/parse the file first to extract valid JSON fragments and than pass it to e.g. GSON library to convert them to objects.
If these will be small files like from your example, you can just load the whole file to string and try use regular expressions (with groups) and/or StringTokenizer to extract JSON chunks.
Related
I have a form that allows me to input data about a single Item. Every time someone submits an Item, I want to add it to a JSON array, which is stored in a file.
Here's my code:
for (Item obj : list) {
out.print(obj.getId());
out.println("");
out.print(obj.getProductName());
out.println("");
out.print(obj.getPrice());
out.println("");
out.print(obj.getType());
out.println("");
}
ObjectMapper mapper = new ObjectMapper();
File file=new File("D:\\extern_2\\src\\java\\JSON\\jsonlist.json");
if (!file.exists()) {
file.createNewFile();
}
PrintWriter print = new PrintWriter(new BufferedWriter(new FileWriter(file, true)));
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.writerWithDefaultPrettyPrinter().writeValue(print, list);
The problem is that every time I add a new Item, a new JSON array is created and appended to the existing file contents.
Desired output:
[ {
"id" : 56,
"productname" : "kklll",
"price" : "56",
"type" : "Hot Coffee",
"productName" : "kklll"
} , {
"id" : 89,
"productname" : "llll",
"price" : "43",
"type" : "Drinks",
"productName" : "llll"
} ]
Actual output:
[ {
"id" : 56,
"productname" : "kklll",
"price" : "56",
"type" : "Hot Coffee",
"productName" : "kklll"
} ][ {
"id" : 89,
"productname" : "llll",
"price" : "43",
"type" : "Drinks",
"productName" : "llll"
} ]
Why is it appending a new array instead of adding my new Item to the existing array?
Look at the FileWriter you are creating: new FileWriter(file, true). That second parameter tells the FileWriter to simply append information to the end of the file. If you are modifying existing JSON, you will need to overwrite the file every time. This means that the first time you create an Item, the ObjectMapper will write it out as a valid JSON string, representing an array with a single object. The second time you create an Item, it will do the same thing for your new object, creating an array with only one object (the second Item) and writing it to the file, even though that file already contains an array. At no point are you actually looking at the file to see if it contains any existing data. You are also not parsing your file into JSON, which would allow you to take an existing JSON array and add something to it.
Your process should be like this:
Read in your existing data in your file, using the ObjectMapper. Since your file contains an array of Item objects, you should end up with a List<Item> after you've read in your file
Add your new Item to the List
Convert your List<Item> to JSON and write it to your .json file. Make sure to overwrite your .json file, not just append to it.
I have a json file which is mostly standard for all my work, the only difference is few parameters.
Now I want to know how can I using java use this json file as a template and provide the parameters as input and save the new json file on local directory?
{
"key" : "HWM_NAME",
"value" : "PINE_SLS_SVC_CUST_CNTCT"
}, {
"key" : "TOPIC",
"value" : "SLS_SVC_CUST_CNTCT2"
}, {
"key" : "SRC_SCHEMA",
"value" : "party_pkg"
}, {
"key" : "SRC_TABLE",
"value" : "SLS_SVC_CUST_CNTCT"
}, {
"key" : "TGT_SCHEMA",
"value" : "mstrdata_hub"
}, {
"key" : "TGT_TABLE",
"value" : "SLS_SVC_CUST_CNTCT"
} ]
},
So here I wish to just change the Value: "PINE_SLS_SVC_CUST_CNTCT" to some other value that I would take as input from user and give me a new json file with those values.
PS: I am working on Java Swing to create a GUI to get the parameters from the user and provide the json file as output.enter image description here
this is how GUI looks
Consider using some JSON Library, for example GSon
Read the values from json
List<LinkedTreeMap> values = gson.fromJson(json, ArrayList.class);
...
update the values, here you can write values from UI components!!!!
for (LinkedTreeMap pair : values) {
//Update values
System.out.println(pair.toString());
}
And generate JSON from java objects
import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
...
Gson gson = new Gson();
String json = gson.toJson(values);
I'm not sure about how to store data about individual users in a golf program that I'm designing (each user needs to have their previous holes etc tracked and logged) in Java
I was wondering if there is a way to store this data without needing to create an individual file for each user?
Any help is much appreciated!
Thanks
You could store this as JSON instead, E.G:
{
"Arnold Palmer" : {
"handicap" : "2",
"history" : {
"1" : {
"courseName" : "St Andrews",
"holeNumber" : "1",
"score" : "2"
},
"2" : {
"courseName" : "St Andrews",
"holeNumber" : "2",
"score" : "3"
}
... etc
}
},
"Tiger Woods" : {
"handicap" : "4",
"history" : {
"1" : {
"courseName" : "Pebble Beach",
"holeNumber" : "1",
"score" : "4"
},
"2" : {
"courseName" : "Pebble Beach",
"holeNumber" : "2",
"score" : "6"
}
... etc
}
}
Then, just parse it when the program starts up and extract the info you need for that user (there are libraries you can use for this). I would suggest that JSON is a more suitable data format for your needs as you need to store dynamic, graph-like data. CSV files are excellent for more simple data sets.
I would still think it better to keep to a seperate file per user though as it will save you having to read through one huge file to find the data you need. Depends how many users you will have though.
Also, if you need to persist data between users, have a shared file for this (e.g. highscores).
If you don't need the files to be exported to another program/system, you can stop caring about its format and start thinking about creating a class hierarchy for your model, which eventually will rely upon Java object serialization:
Writing objects to a file:
MyObject obj1=...;
MyObject obj2=...;
try (ObjectOutputStream output=new ObjectOutputStream(new FileOutputStream(file)))
{
output.writeObject(obj1);
output.writeObject(obj2);
}
Reading objects from a file:
try (ObjectInputStream input=new ObjectInputStream(new FileInputStream(file)))
{
MyObject obj=(MyObject)input.readObject();
}
You just need to ensure that your class (MyObject in the upper example) implements java.io.Serializable, as well as every class involved in its definition (member variables and its subsequent definitions).
You can calso serialize/parse a collection of objects, as long as you chose a serializable implementation of Collection (for example java.util.ArrayList).
In Java the easiest way to store key-value pairs are properties files, e. g.:
Write:Properties prop = new Properties();
prop.setProperty("user1.prevHole", "foo");
prop.store(new FileOutputStream("golf.properties"), null);
Read:Properties prop = new Properties();
prop.load(new FileInputStream("golf.properties"));
String prevHole = prop.getProperty("user1.prevHole");
See Java Properties file examples
I have this two documents in my mongoDB database:
db.DocumentFile.find().pretty()
{
"_id" : ObjectId("587f39910cc0fec092bdb10c"),
"_class" : "com.smartinnotec.legalprojectmanagement.dao.domain.DocumentFile",
"fileName" : "DocumentFile1",
"ending" : "jpg",
"projectId" : "587f39910cc0fec092bdb10b",
"active" : true,
"userIdBlackList" : [
"587f39910cc0fec092bdb10a"
]
}
{
"_id" : ObjectId("587f39910cc0fec092bdb10d"),
"_class" : "com.smartinnotec.legalprojectmanagement.dao.domain.DocumentFile",
"fileName" : "DocumentFile2",
"ending" : "jpg",
"projectId" : "587f39910cc0fec092bdb10b",
"active" : true,
"userIdBlackList" : [ ]
}
I have this code in order to get amount of query:
final Query query = new Query();
query.addCriteria(Criteria.where("userIdBlackList").nin(userId));
final Long amount = mongoTemplate.count(query, DocumentFile.class);
return amount.intValue();
The amount is 2 in this case what is wrong - it should be 1.
The query in Query object looks like this:
Query: { "userIdBlackList" : { "$nin" : [ "587f39910cc0fec092bdb10a"]}}
If I copy this query and made a query for the mongodb console like this:
db.DocumentFile.find({ "userIdBlackList" : { "$nin" : [ "587f39910cc0fec092bdb10a"]}}).pretty()
I get an amount of two, what if wrong because one document includes 587f39910cc0fec092bdb10a in userIdBlackList -> it should be one.
With this query command:
db.DocumentFile.find({userIdBlackList: { "$nin": ["587f39910cc0fec092bdb10a"] } }).pretty();
I get the right result, I am really confused at the moment.
Does anyone have any idea?
Maybe the problem ist that one time userIdBlackList is with quotation mark ("userIdBlackList") and the other time it isn't.
I think the problem is with the unintentional formatting picked up for "userIdBlackList". Your string is interpreted with non printing characters in the "??userIdBlackList" for all your search queries. I see little transparent square boxes when I copy your queries to mongo shell.
That tells me their is some encoding issue. Clear that formatting and see if that helps you.
Both $ne and $nin should work!
I need the String property of object to be serialized as nested JSON without any escaping etc. So given json:
{
"regularProperty" : "Test here",
"nestedJSON" : {
"propertyArray" : [1,2,3],
"propertyText" : "new Text",
"anotherObject" : { ... }
}
}
And the nestedJSON property must contain the text
{
"propertyArray" : [1,2,3],
"propertyText" : "new Text",
"anotherObject" : { ... }
}
How is it possible for both serialization/deserialization? Any specific annnotation or data type?
Maybe add the annotation JsonRawValue on the nestedJSON field? I never used it before but it seems quite promising for your case.