I need some Java help.
I have got a class like this
public class Thing {
private String name;
private int price;
public Thing(String name, int price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
And my main looks like this
public class Main {
public static void main(String[] args) {
Thing Bowl = new Thing("Bowl", 20);
} }
What I would like to do is make a simple XML-document database. So I can add different kind of things in my database. How can I implement this kind of database in my system?
It's not correct to call what you're talking about a database. You just want to save a Java class as an XML file. Jackson is a good library that allows for both JSON and XML encode/decode and using it, can be done as so given a POJO:
ObjectMapper xmlMapper = new XmlMapper();
List<Thing> things = new ArrayList<>();
things.add(bowl);
String xmlData = xmlMapper.writeValueAsString(things);
List<Thing> thingsFromXml = xmlMapper.readValue(xmlData, new TypeReference<List<Thing>>(){});
Although the question is very broad, I'll do my best to guide you along.
An overarching system for XML consists out of various subsystems. First of all, you're going to need a way to parse the XML documents. There are many open source libraries out there that you can use. Even if you insist on writing it from scratch, referencing work that others have made is always useful.
See this:
Which is the best library for XML parsing in java
Then once you have a system in place in which you can parse the documents, you'll need a way to organize the parsed data. The way to approach this is subject to the practical use of the system. For example, if you use XML as the standard format for loading data in a game and thus deal with many different types of data such as items, objects, locations and so forth. You'll want a dynamic way to reload the data, the factory design pattern would work well in this use-case.
See this: https://www.tutorialspoint.com/design_pattern/factory_pattern.htm
Related
I already have PHP to pull the info from MySQL and encode to json, example output below:
[{"name":"Player A","score":1459},{"name":"Player B","score":1434}]
I'm struggling to follow guides where I can parse this into a listview. For a start, it seems massively overcomplicated, needing custom adapters, large custom classes defining everything etc
Am I being naive thinking there should be an easy way to read this data from a URL and assign to a listview? I only need name and score fields for a basic scoreboard.
Even if I could just split the entire output up into strings, this would be more than enough as I could then do textview.setText(string1) and so on ...
If anyone has a working example of pulling json from a URL and being able to either pass this to a listview, or if its simpler, to be able to pass the output to strings?
Better use RecyclerView for parsing the json data.This link is the most simplest way to parse the json data.
http://androidcss.com/android/fetch-json-data-android/
Try it :)
Create a class SimpleModel.java
public class SimpleModel {
private int score;
private String name;
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
and parse it using Gson like this
String YOUR_RESPOSE_STRING = "";
Gson gson = new Gson();
Type lisType = new TypeToken<ArrayList<SimpleModel>>() {
}.getType();
ArrayList<SimpleModel> list = gson.fromJson(YOUR_RESPOSE_STRING, lisType);
I'm calling an API of some service and they return a gigantic JSON with literally around a hundred of fields and a dozen of nested objects. However, I don't need all of them. In fact, when doing GET or POST I really need from 3 to 7 fields. I very much want to avoid having this complex model in my application just to serialize/deserialize a couple of fields.
Essentially, I wanted to achieve:
Deserialize their gigantic nested JSON string to my flat POJO.
Work in my code with my flat POJO projection.
Serialize my flat POJO to their complex nested schema.
My solution so far was to rely on JsonPath:
Create a custom annotation for fields in my flat POJO, like:
#JsonPathField("$.very.deeply.nested.field.value")
private String theOnlyFieldIneed;
Create a util method that uses reflection to produce a map of <fieldName, JsonPath.readValue()> which I give to Jackson objectMapper to produce my POJO. So deserialization to a flat POJO part works.
For serialization, however, things are worse, because JsonPath throws an exception if the path doesn't exist in the String. Like,
// This will throw an exception:
DocumentContext document = JsonPath.using(jsonPathConfig).parse("{}");
document.set("$.not.even.deepest", value);
To workaround that, I added kinda original schema as a string to feed to JsonParh.parse(Pojo.Prototype) but this is ugly, tedious and error-prone.
Basically, I'm looking for Immutable.JS kind of behaviour: Collection.SetIn
You could use Kson (https://github.com/kantega/kson) which has a pretty straighforward support for extracting values from nested structures.
public class DecodeExample {
public static class Address {
final String street;
final String zip;
public Address(String street, String zip) {
this.street = street;
this.zip = zip;
}
}
static class User {
final String name;
final Address address;
User(String name, Address address) {
this.name = name;
this.address = address;
}
}
public static void main(String[] args) {
final JsonDecoder<Address> adressDecoder =
obj(
field("street", stringDecoder),
field("zip", stringDecoder.ensure(z -> z.length() < 5)), //You can add constraints right here in the converter
Address::new
);
JsonResult<JsonValue> json =
JsonParser.parse(jsonString);
Address address =
json.field("model").field("leader").field("address").decode(adressDecoder).orThrow(RuntimeException::new);
System.out.println(address);
JsonResult<Address> userAddress =
json.field("model").field("users").index(0).field("address").decode(adressDecoder);
System.out.println(userAddress);
}
}
As the title says....
I want to build a POJO with four field variables and at certain runtime events create an instance of this POJO with access to possibly maybe two or three of the fields.
public class Category implements Serializable {
private String name;
private String description;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
Lets say I create a new Category object but I only want to be able to have access to the name field during runtime. Is there a design pattern I can use to achieve this? I thought about the strategy pattern and looked at the builder but I am still confused if I can do this in java.
Basically the overall goal is to grab an object from a database and return it as a JSON response in jax rs. But sometimes I dont want a complete object returned but only lets say halve of the object to be accessible at during certain runtime events. My apologies if this seems like a dumb question but I know what I want to do but just don't know the best way.
I have the same problem with you, and my project was used springmvc,and the json tool is jackson.With the problem solved, I just use #JsonIgnore.For more details,just read jackson-how-to-prevent-field-serialization
So someone correct me if I am wrong or see a better option than this...with alot of objects this can be alot of extra code for serialization and deserialization...Jackson Provisions is what I need. I can use the annotation #JsonView(DummyClass.class) on the field variable. I will accept this a the best answer in a day or two unless someone else posts a better response.
// View definitions:
class Views {
static class Public { }
static class ExtendedPublic extends PublicView { }
static class Internal extends ExtendedPublicView { }
}
public class Bean {
// Name is public
#JsonView(Views.Public.class) String name;
// Address semi-public
#JsonView(Views.ExtendPublic.class) Address address;
// SSN only for internal usage
#JsonView(Views.Internal.class) SocialSecNumber ssn;
}
With such view definitions, serialization would be done like so:
// short-cut:
objectMapper.writeValueUsingView(out, beanInstance, ViewsPublic.class);
// or fully exploded:
objectMapper.getSerializationConfig().setSerializationView(Views.Public.class);
// (note: can also pre-construct config object with 'mapper.copySerializationConfig'; reuse)
objectMapper.writeValue(out, beanInstance); // will use active view set via Config
// or, starting with 1.5, more convenient (ObjectWriter is reusable too)
objectMapper.viewWriter(ViewsPublic.class).writeValue(out, beanInstance);
This information was pulled from http://wiki.fasterxml.com/JacksonJsonViews
with jackson 2.3, I can do this with JAX-RS
public class Resource {
#JsonView(Views.Public.class)
#GET
#Produces(MediaType.APPLICATION_JSON )
public List<Object> getElements() {
...
return someResultList;
}
}
We are working on a multi process projects which use RMI for RPCs.
The problem that we are facing is that the main object which must be passed between processes is very big (when serialized), and this dropped the performance of the code dramatically.
Since, none of the processes change the whole object and only alter small parts of it, we decided to just pass "the modifications" through RMI.
but I found no proper way to implement such concept. The first idea was to keep track of all changes of the main instance. But this seems not easy according to this.
I need a way which we can:
develop fast
performs fast
any suggestion?
Just make this 'main object' a remote object that implements a remote interface, and export it, instead of serializing it backwards and forwards.
I think the best way is to customize your serialization so you will be able to send only the changes. you can do it by implementing private method of
private void writeObject(java.io.ObjectOutputStream stream) and of course also readObject from the other side. well, what you should do in this functions?
I suggest you will manage a bitmap of all the members that were changed and only send them in the serialization, just change the unchanged members to null send the object in serialization and than return there values. in the other side read the bitmap and than you will know how to
First time you need to pass the whole object.
Use PropertyChangeListener on the object, this would generate an PropertyChangeEvent.
You can pass the PropertyChangeEvent around. It has the getSource(), by which you can identify the object. If this is not enough, if you need IOR or any other sort of reference, create a wrapper and sent it across..
-Maddy
Have a look to http://docs.oracle.com/javase/tutorial/uiswing/events/propertychangelistener.html
public class Test {
PropertyChangeSupport pcs = new PropertyChangeSupport(this);
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
String oldName = this.name;
this.name = name;
pcs.firePropertyChange("name", oldName, name);
}
public int getAge() {
return age;
}
public void setAge(int age) {
int oldAge = this.age;
this.age = age;
pcs.firePropertyChange("age", oldAge, age);
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
pcs.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
pcs.removePropertyChangeListener(listener);
}
public Test(){
}
public static void main (String[] args){
Test myTestObject = new Test();
myTestObject.addPropertyChangeListener(new MyPropertyChangeListener());
myTestObject.setAge(12);
myTestObject.setName("Rick");
myTestObject.setName("Andrew");
}
private static class MyPropertyChangeListener implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent event) {
String clazz = event.getSource().getClass().getName();
System.out.println(clazz+"::"+event.getPropertyName()+" changed from "+event.getOldValue()+" to "+event.getNewValue());
}
}
}
This is a simple example but using this approach you can create different PropertyChangeListeners and provide different logic inside theirs method propertyChange.
Also is possible to fire only the changes over a small set of attributes and not over all of them (not storing the oldValue and not firing the firePropertyChange method of PropertyChangeSupport).
Of course that you can use AOP, but perhaps you are looking for a solution like presented above. I hope this helps.
I am trying to convert an XML file to a Java Object, now, I have read of JAXB, XStream, Sax and DOM, I'd like to convert this sort of type of xml:
<testxml testtype="converting" duration="100.00" status="successful" />
it might be as well as:
<testxml testype="converting" duration="100.00"> successful </textxml>
I wanted to know if there is anything out there (and possibly not 3rd party) that I can use, without declaring a template in DTD or in JAXB in XSD but Java (therefore I will declare a java class called testxml with all the relevant variable i.e. testtype, duration, status>
Thank you all for your time.
The class below using JAXB Annotations will do exactly what you need, no need to create an XSD or a template using Java 1.6+:
#XmlRootElement
public class TestXML {
private String testtype;
private double duration;
private String status;
public void setTesttype(String testtype) {
this.testtype = testtype;
}
#XmlAttribute
public String getTesttype() {
return testtype;
}
public void setDuration(double duration) {
this.duration = duration;
}
#XmlAttribute
public double getDuration() {
return duration;
}
public void setStatus(String status) {
this.status = status;
}
#XmlValue
public String getStatus() {
return status;
}
public static void main(String args[]) {
TestXML test = JAXB.unmarshal(new File("test.xml"), TestXML.class);
System.out.println("testtype = " + test.getTesttype());
System.out.println("duration = " + test.getDuration());
System.out.println("status = " + test.getStatus());
}
}
Using this as test.xml:
<testxml testtype="converting" duration="100.00"> successful </testxml>
You can do this pretty simply by using java.xml.bind.annotations on a Java class and JAXB.Unmarshal
JAXB is part of the JRE in java 1.6+
Try XStream/XPP3. That's good stuff. Takes a couple of hours to figure out. Does all the magic for you.
Personally I use XStream # http://x-stream.github.io/ It's really easy to use and still offers enough features in case you need them. Unfortunately it looks like the project is not actively maintained anymore, but I haven't seen an alternative so far that suits my needs as well. I'd say it's worth spending a bit of time to check it out ;-)
edit: when you can use Java 6, I completely agree the other answers are preferable!