HTML in a JSON String in Java - java

I want to save a Java class named MyClass into a text file and I want to use JSON to encode the class for file writing purposes instead of implementing the Serializable interface. Moreover, to save the class I want to use the Google's Gson library and in particular the JsonWriter class. The MyClass class is, for instance, defined as follows:
public class MyClass{
String html;
public MyClass(){}
}
As shown in the example above, MyClass has a String field named html, that obviously must contain HTML code.
Can I save the class into a text file by using JSON via the JsonWriter or I should encode or do something similar with the html field (e.g. a call to an URLEncode-like function) before to give it to JsonWriter?

Since escaping new lines / quotes etc can make this a little tricky, why not just use XStream to convert the object to XML and wrap the HTML in a CDATA section ? Json has no equivalent for a CDATA section.

Related

How to generate class file with dynamic property names

Suppose I have source java template as:
public class Class1 {
private String field1;
private int field2;
}
In my main method I want to generate above template java class as follows
It should generate separate MyClass.java file in different location
Class1 should be replace as MyClass
field1 should be replace as property1
field2 should be replace as property2
Example:
public class MyClass{
private String property1;
private int property2;
}
Is there any framework to achieve this? We can give dynamic names in xml file .
Maybe you are looking at http://commons.apache.org/proper/commons-bcel/index.html
The Byte Code Engineering Library (Apache Commons BCEL™) is intended to give users a convenient way to analyze, create, and manipulate (binary) Java class files (those ending with .class). Classes are represented by objects which contain all the symbolic information of the given class: methods, fields and byte code instructions, in particular.
Here https://www.programcreek.com/java-api-examples/index.php?api=org.apache.bcel.generic.ClassGen you can find some examples of how to use ClassGen
This article also could be useful https://www.ibm.com/developerworks/java/library/j-dyn0414/.

Java Object to JSON Conversion

I have a Java object as below
public class Command {
private String cmd;
private Object data;
}
I want JSON Conversion of this Object to look as below
{"cmd":"getorder","data":{"when":"today"}}
How do I do this without changing the Class definition?
I know how to use GSON or Jackson library. I am having trouble assigning values to or initializing (Object) data above, so that it properly converts to {"when":"today"} when I use those libraries.
Thanks
You can try Gson library
it's very easy to use and it can do the reverse operation as well
Depending on your needs you might consider to add a handwritten json formatter for your class (of yourse this interferes with your demand to not change the class definition) but in fact it gives you max flexibility without 3rd party dependencies. If you strictly let all your Objects overwrite toString() to give json formatted string representation you could e.g.
String toString() {
StringBuffer result = new StringBuffer();
result.add("{ \"cmd\":" + this.cmd);
result.add(",");
result.add( \"data\":" + data.toString());
result.add("}");
return result.toString();
}
In case your need to not change the class definition appears more important than the mentioned advanteges there is a a nice json library avaialble on code.google.com named "simple json" ( https://code.google.com/p/json-simple/ ).

Lookup.getDefault().lookup() returns null

What should be done if a lookup returns null? I am using Lookup.getDefault().lookup() of org.openide.util.Lookup which is used for finding instances of objects. The general pattern is to pass a Class object and get back an instance of that class or null.
I am using it in the code below:
StreamingServer server = Lookup.getDefault().lookup(StreamingServer.class);
ServerControllerFactory controllerFactory = Lookup.getDefault().lookup(ServerControllerFactory.class);
StreamingController controller = Lookup.getDefault().lookup(StreamingController.class);
Since no istances are found, null is returned for each of these, 'server', 'controllerFactory', 'controller'. I need to handle this situation so I can use these objects to access methods, as in :
controllerFactory.createServerController(graph)
server.register(serverController, context)
How can I accomplish this?
You need to create a META-INF/services folder in your Eclipse source folder. Then, for each class, create a text file in the META-INF/services folder. The name of the text file is the full name (includes the package location) of the class type, and the contents of the text file is the full name (includes the package location) of the implementing class (which is not necessarily the same name of the class).
For example, for the ServerControllerFactory class, you will create a text file named org.gephi.streaming.server.ServerControllerFactory and the text this file will contain is org.gephi.streaming.server.impl.ServerControllerFactory
For me, the class that I was trying to call lookup on just needed the #ServiceProvider decoration like this:
#ServiceProvider(service = MyClassHere.class)
public final class MyClassHere ....

Parse Java class (for code representation) to JSON object

In an android application I'm developing I need to get a json file containing some data to reconstruct the lines of code of a java class.
Is there any java/javascript library that allows to convert/parse a java class (that doesn't just have fields, but also methods defined inside it) in JSON format, and vice-versa?
EDIT: I'd also need to keep track of the whole project's structure (something like antlr?)
EDIT2: My bad, I wanted to store a java class code into a JSON object to represent it, I was also thinking to create my own json object, this way, by parsing the Java code and finding methods, classes, parameters.
{
"file": "PATH/TO/.java",
"language": "java",
"from": 0,
"to": 255,
"classes": [
"Test:2"
//...
],
"lines": [
[
"public class Test{"
//...
]
]
}
But if a good starting point is present, that would be great.
The trouble is that existing tools (such as GWT) are "only" able to create functioning JS code that is meant to be executed in browsers. But it does not necessarily resemble the original Java class. Your use case sounds quite different. It looks like you want to represent Java source code as JSON data and you don't need/want to execute it.
I fear you may have to create your own tool for that, that meets your specific requirements. I also fear that this tool must be able to parse the Java code because using simple regexes for extracting the data won't help here much because of nested types (interfaces, classes, enums) and also because a single Java file may contain multiple type declarations (even though not encouraged, but it is possible).
Here are a few links for Java parsers:
http://code.google.com/p/javaparser/ (unfortunately only Java 1.5)
http://www.ibm.com/developerworks/opensource/library/os-ast/ (discusses the Eclipse Java parser which is very robust and probably most suitable for your requirement)
You could also create your own parser using ANTLR as you suggest. The latest ANTLR version has some visitor pattern you need to implement in Java, as far as I know. You could implement a visitor that successively constructs your JSON output.
However, you really should use Eclipse's ASTParser for that, because you can easily iterate all methods of your class and get their implementation code as String.
You can use jackson library - http://jackson.codehaus.org/: http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/
Use GSON: "GOOGLE for JSON" it's a google open source JSON Library, it can convert Java Object t o JSON object and vice-versa
You have Gson package that convert Json String to Java object and vice versa.
MyClass.java
public class MyClass {
private String mStr = "";
public String getStr() {
return mStr;
}
public void setStr(String mStr) {
this.mStr = mStr;
}
}
Main.java
public class Main {
public static void main(String[] args) {
String jsonString = "{ \"mStr\": \"foo\" }";
Gson mGson = new Gson();
MyClass res = mGson.fromJson(jsonString, MyClass.class);
System.out.println(res.getStr());
}
}
Output: foo
[Edit 1]
You can't store to Json class structure, only data
[Edit 2]
From your fix I understand followed thing:
This Json String represents behavior what to do with "text" file , suppose, you download from server. But no mater what inside Json String 1st of all you need to convert it to Object in Java (if you want to use Java) and after that according to rules (took from Json String) write any logic. For sure java code is able to generate Java files. Your example tells you:
to get text from line ... to line,
create file named xxxx.java
copy it to ...
So use my example above, create class, lets say Launcher:
public class Launcher{
private String file;
private String language;
private int from;
private int to;
private List<String> classes;
private List<SomeOtherClass> lines;
....
}

How can I make pre-configured templates using XStream

I am currently developing a system that uses XStream to create objects from XML. An example object would be
#XStreamAlias("TestClass")
public class TestClass{
#XStreamAlias("format")
private String format;
public String getFormat(){
return format;
}
public void setFormat(String format){
this.format = format;
}
}
This class has one field, a format field, and the XML from which it would be constructed would look like:
<TestClass>
<format>foo</format>
</TestClass>
Now I would like to instantiate different instances of this class, with a specific format. For instance I would like a TestClass object with format foo and one with format bar. But instead of producing
<TestClass>
<format>foo</format>
</TestClass>
<TestClass>
<format>bar</format>
</TestClass>
I want to use an alias system of some sort so that the above XML would not be necessary but instead I could use
<TestClassFoo />
<TestClassBar />
where of course the name does not need to include the format specified.
I see that there has to be a custom converter, but I again do not want to hard code every alias, but instead load these from XML as well (yes, it get complicated). The result of this would be to create shortcut templates for different XML objects, which can be configured dynamically.
If your goal is more compact XML, why not use #XStreamAsAttribute so you will get output like <TestClass format="foo"/>? Otherwise, yes, you are going to have to write a custom converter to do exactly what you want.

Categories

Resources