Parse Java class (for code representation) to JSON object - java

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

Related

Convert Json to multiple pojo java classes types using GSon when exact root class is not known

I use GSon to convert JSon coming from various sources to appropriate java objects. The requirement is: My applications could be receiving json of unrelated classes, Class A, Class B, Class C via multiple sources via sync/async but I want to keep the root class/model of all the pojo same.
PS- I can use any other library other than gson as well. So suggestions are welcome :)
Suppose I have these 2 possible JSON responses:
{
"schoolData": {"schoolName": "100"}
}
or
{
"countryData": {"region": "asia"}
}
I want to create a base class like this over all other sub classes so I need not to write below line separately for different classes .
BaseModelClass root = om.readValue(myJsonString, BaseModelClass.class);
public class BaseModelClass{
private SchoolModelClass schoolModelClass;
private CountryModelClass countryModelClass;
//more possible responses...
//getters and setters...
}
public class SchoolModelClass {
SchoolData schoolData;
}
How to instantiate SchoolModelClass when schooldata is received and similarly for others since they all are inside one baseModelClass.

Instantiate a java class in python and send it back to java

I have a class in java:
public class MyClass{
public String a=null;
public String b=null;
public String c=null;
public String d=null;
public static String testMyClass() {
//my method instruction using the attributes a,b,c and d
}
The trouble is that MyClass attributes must be received from python to be able to use the method testMyClass. So is it possible to instantiate a java class from python and after send it back to java using py4j?
Anyone can show how to make it if it is possible? Or have another alternative?
I don't think that is possible unless someone knows of a "bridge" utility between Java and Python.
However, you may do this:
Create a JSON in the Python script in a structure that matches that of MyClass
Receive it in your Java method and deserialize the JSON into an instance of MyClass using Jackson or some JSON tool.
Your next problem will be the communication between you Java process and Python process. For that, see if this StackOverflow question helps: Passing data from Java process to a python script

swagger-codegen simple models missing

I'm realizing my second API with swagger/swagger-codegen.
After having a really good start with my first one I'm somewhat stuck with the following problem:
I'm having multiple definitions like the following:
TopIssueReference:
description: Id of a top issue
type: string
example:
itemid: 'd32c1213-4773-442e-9c5f-f5d516358869'
All those definitions only are aliases for type string, some with format date-time, some naked like the one above.
The swagger editor is fine with those definitions.
When I use one of them in a $ref clause within some object definition the generator produces a reference to a class named like my definition, TopIssueReference in this case.
The generated TopIssueReference class is the following (in java):
#ApiModel(description = "Id of a top issue")
public class TopIssueReference {
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class TopIssueReference {");
sb.append("}");
return sb.toString();
}
}
which is not really useful.
Does anybody have an idea what's going wrong here?
Shouldn't the generator either produce a reference to a String or at least make TopIssueReference derive from a string (however useful that may be)?
For some of those definitions, the generator does not generate any class at all - but the references are still there, so the resulting code does not even compile.
I tried generating servers and clients with java and python, and both are having the same problem.
Try Bellow code to your swagger file to generate code.
TopIssueReference:
description: Id of a top issue
type: object
properties:
itemid:
type: string
i hope it's useful to you ...!

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/ ).

HTML in a JSON String in 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.

Categories

Resources