Skip to content

Commit c5d938a

Browse files
author
seal
committed
Add support for jsonArray string
Some optimize
1 parent fdee57a commit c5d938a

File tree

12 files changed

+180
-27
lines changed

12 files changed

+180
-27
lines changed

README.md

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,56 @@ I am a plugin for Kotlin to convert Json String into Kotlin data class code (Jso
1616

1717
![alt text](https://plugins.jetbrains.com/files/9960/screenshot_17276.png)
1818

19+
### Generate Example
20+
* example with none json lib support and comment option on
21+
22+
```kotlin
23+
data class FD(
24+
val programmers: List<Programmer>,
25+
val authors: List<Author>,
26+
val musicians: List<Musician>
27+
)
28+
29+
data class Musician(
30+
val firstName: String, //Eric
31+
val lastName: String, //Clapton
32+
val instrument: String //guitar
33+
)
34+
35+
data class Author(
36+
val firstName: String, //Isaac
37+
val lastName: String, //Asimov
38+
val genre: String //science fiction
39+
)
40+
41+
data class Programmer(
42+
val firstName: String, //Brett
43+
val lastName: String, //McLaughlin
44+
val email: String //aaaa
45+
)
46+
47+
```
48+
* example with gson option on
49+
50+
```kotlin
51+
52+
data class FD(
53+
@SerializedName("214123addre++/-*ssbook") val addressbook: List<addressbook>
54+
)
55+
56+
data class addressbook(
57+
@SerializedName("*-/-+address") val address: address,
58+
@SerializedName("name") val name: String, //Ann Michaels
59+
@SerializedName("phoneNumbers") val phoneNumbers: List<String>
60+
)
61+
62+
data class address(
63+
@SerializedName("city") val city: List<String>,
64+
@SerializedName("*-/32432-*/4street") val street: List<String>,
65+
@SerializedName("zip") val zip: List<Int>
66+
)
67+
68+
```
1969

2070
### More Detail Document
2171
* http://blog.csdn.net/wuseal/article/details/77508585

src/wu/seal/jsontokotlin/ClassName.kt

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ object KClassName : IKClassName {
2020

2121
private val ilegalCharactor = listOf<String>(
2222
"\\+", "\\-", "\\*", "/", "%", "=", "&", "|", "!", "\\[", "\\]", "\\{", "\\}", "\\(", "\\)"
23-
, ",", ".", ":", "\\?", "\\>", "\\<", "@", ";","'", "\\`","\\~" ,"\\$", "^", "#", "\\", "/", " "
23+
, ",", ".", ":", "\\?", "\\>", "\\<", "@", ";", "'", "\\`", "\\~", "\\$", "^", "#", "\\", "/", " "
2424
)
2525

2626
private val suffix = "X"
@@ -30,12 +30,29 @@ object KClassName : IKClassName {
3030

3131
val pattern = "${ilegalCharactor}"
3232

33-
val temp = rawClassName.replace(Regex(pattern), "")
33+
val temp = rawClassName.replace(Regex(pattern), "").let {
34+
35+
return@let removeStartNumber(it)
36+
37+
}
3438

3539
return if (temp in ilegalClassNameList) {
3640
return temp + suffix
3741
} else {
3842
temp
3943
}
4044
}
45+
46+
/**
47+
* remove the start number characters in this string
48+
*/
49+
private fun removeStartNumber(it: String): String {
50+
return if (it.indexOfFirst {
51+
return@indexOfFirst it in '0'..'9'
52+
} == 0) {
53+
it.replaceFirst(Regex("\\d{1,}"), "")
54+
} else {
55+
it
56+
}
57+
}
4158
}

src/wu/seal/jsontokotlin/GsonSupporter.kt

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
package wu.seal.jsontokotlin
22

33
/**
4+
* Gson Support about
45
* Created by Sea.Wu on 2017/9/18.
56
*/
67

78
/**
89
* When target Json lib is Gson, this prove fun to create Last Property String block
910
*/
10-
interface IGsonSupportor {
11+
interface IGsonSupporter {
1112
/**
1213
* create property String block to fit Gson at most
1314
*/
@@ -16,7 +17,7 @@ interface IGsonSupportor {
1617
}
1718

1819

19-
object GsonSupportor : IGsonSupportor {
20+
object GsonSupporter : IGsonSupporter {
2021

2122
/**
2223
* When adapter Gson lib at most ,We should import the Anotation Class

src/wu/seal/jsontokotlin/ImportClassWriter.kt

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import com.intellij.openapi.editor.Document
66
import com.intellij.openapi.project.Project
77

88
/**
9-
* to be Import class declare code insert helper
9+
* to be a helper to insert Import class declare code
1010
* Created by Seal.Wu on 2017/9/18.
1111
*/
1212

@@ -52,15 +52,15 @@ object ImportClassWriter : IImportClassWriter {
5252

5353
override fun insertGsonImportClass(project: Project, editFile: Document) {
5454
val text = editFile.text
55-
if (GsonSupportor.gsonAnotationImportString !in text) {
55+
if (GsonSupporter.gsonAnotationImportString !in text) {
5656

5757
val index = Math.max(text.lastIndexOf("import"), 0)
5858
val tobeInsertEndline = editFile.getLineNumber(index)
5959
val insertIndex = if (index == 0) index else editFile.getLineEndOffset(tobeInsertEndline)
6060

6161
CommandProcessor.getInstance().executeCommand(project, {
6262
ApplicationManager.getApplication().runWriteAction {
63-
editFile.insertString(insertIndex, "\n" + GsonSupportor.gsonAnotationImportString + "\n")
63+
editFile.insertString(insertIndex, "\n" + GsonSupporter.gsonAnotationImportString + "\n")
6464

6565
}
6666
}, "insertKotlin", "JsonToKotlin")
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package wu.seal.jsontokotlin
2+
3+
import com.google.gson.Gson
4+
import com.google.gson.JsonArray
5+
import com.google.gson.JsonElement
6+
import com.google.gson.JsonParser
7+
import java.util.*
8+
9+
/**
10+
* Target Json Element Maker form a String or an Element for generating Code
11+
* Created by Seal.Wu on 2017/9/19.
12+
*/
13+
interface ITargetJsonElement {
14+
/**
15+
* get excpected jsonElement for generating kotlin code
16+
*/
17+
fun getTargetJsonElementForGeneratingCode(): JsonElement
18+
}
19+
20+
21+
class TargetJsonElement : ITargetJsonElement {
22+
private val jsonElement: JsonElement
23+
24+
constructor(jsonString: String) {
25+
this.jsonElement = JsonParser().parse(jsonString)
26+
27+
}
28+
29+
constructor(jsonElement: JsonElement) {
30+
this.jsonElement = jsonElement
31+
}
32+
33+
override fun getTargetJsonElementForGeneratingCode(): JsonElement {
34+
if (this.jsonElement.isJsonArray) {
35+
val jsonElementNotArray = getArrayChildElement(this.jsonElement.asJsonArray)
36+
if (jsonElementNotArray.isJsonObject) {
37+
return jsonElementNotArray
38+
}
39+
}else if (this.jsonElement.isJsonObject) {
40+
return this.jsonElement
41+
}
42+
throw IllegalFormatFlagsException("Unsupported Json String")
43+
}
44+
45+
46+
private fun getArrayChildElement(jsonArray: JsonArray): JsonElement {
47+
if (jsonArray.size() >= 1) {
48+
val jsonElement1 = jsonArray[0]
49+
if (jsonElement1.isJsonArray) {
50+
return getArrayChildElement(jsonElement1.asJsonArray)
51+
} else {
52+
return jsonElement1
53+
}
54+
} else {
55+
return Gson().toJsonTree(Any())
56+
}
57+
}
58+
}

src/wu/seal/jsontokotlin/KotlinMaker.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,12 @@ public class KotlinMaker {
2020
private Set<String> toBeAppend = new HashSet<String>();
2121

2222
public KotlinMaker(String className, String inputText) {
23-
this.inputElement = gson.fromJson(inputText, JsonElement.class);
23+
this.inputElement = new TargetJsonElement(inputText).getTargetJsonElementForGeneratingCode();
2424
this.className = className;
2525
}
2626

2727
public KotlinMaker(String className, JsonElement jsonElement) {
28-
this.inputElement = jsonElement;
28+
this.inputElement = new TargetJsonElement(jsonElement).getTargetJsonElementForGeneratingCode();
2929
this.className = className;
3030
}
3131

@@ -71,7 +71,7 @@ private void appendJsonObject(StringBuilder stringBuilder, JsonObject jsonObject
7171
addProperty(stringBuilder, property, type, jsonElementValue.getAsString());
7272
} else if (jsonElementValue.isJsonObject()) {
7373
type = getJsonObjectType(property, (JsonObject) jsonElementValue);
74-
addProperty(stringBuilder, property, type, null);
74+
addProperty(stringBuilder, property, type, "");
7575
} else if (jsonElementValue.isJsonNull()) {
7676
addProperty(stringBuilder, property, type, null);
7777
}

src/wu/seal/jsontokotlin/MakeKotlinClassAction.java

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,6 @@
11
package wu.seal.jsontokotlin;
22

3-
import com.google.gson.Gson;
4-
import com.google.gson.JsonElement;
5-
import com.google.gson.JsonObject;
6-
import com.google.gson.JsonSyntaxException;
3+
import com.google.gson.*;
74
import com.intellij.openapi.actionSystem.AnAction;
85
import com.intellij.openapi.actionSystem.AnActionEvent;
96
import com.intellij.openapi.actionSystem.PlatformDataKeys;
@@ -25,6 +22,7 @@
2522
import javax.swing.text.JTextComponent;
2623
import java.awt.*;
2724
import java.awt.event.ActionEvent;
25+
import java.util.IllegalFormatFlagsException;
2826

2927
/**
3028
* Created by Seal.Wu on 2017/8/18.
@@ -54,13 +52,11 @@ public void actionPerformed(AnActionEvent event) {
5452
}
5553
final Messages.InputDialog inputDialog = new Messages.InputDialog(project, "Please input the Json Data", "Input Json"
5654
, Messages.getInformationIcon(), "", new InputValidator() {
57-
private final Gson gson = new Gson();
58-
5955
@Override
6056
public boolean checkInput(String inputString) {
6157
try {
62-
JsonElement jsonElement = gson.fromJson(inputString, JsonObject.class);
63-
return true;
58+
JsonElement jsonElement = new JsonParser().parse(inputString);
59+
return jsonElement.isJsonObject() || jsonElement.isJsonArray();
6460
} catch (JsonSyntaxException e) {
6561
return false;
6662
}
@@ -123,8 +119,14 @@ protected JComponent createScrollableTextComponent() {
123119
final Document document = editor.getDocument();
124120
ImportClassWriter.INSTANCE.insertImportClassCode(project, document);
125121

126-
final KotlinMaker maker = new KotlinMaker(className, jsonString);
127-
final VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(document);
122+
final KotlinMaker maker;
123+
try {
124+
maker = new KotlinMaker(className, jsonString);
125+
} catch (IllegalFormatFlagsException e) {
126+
e.printStackTrace();
127+
Messages.showErrorDialog(e.getMessage(), "Unsupport Json");
128+
return;
129+
}
128130

129131
CommandProcessor.getInstance().executeCommand(project, new Runnable() {
130132
@Override
@@ -144,7 +146,7 @@ public void run() {
144146
} else {
145147
offset = document.getTextLength() - 1;
146148
}
147-
document.insertString(offset, maker.makeKotlinData());
149+
document.insertString(Math.max(offset, 0), maker.makeKotlinData());
148150

149151
}
150152
});

src/wu/seal/jsontokotlin/NoneSupporter.kt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package wu.seal.jsontokotlin
22

33
/**
4+
*
45
* Created by Seal.Wu on 2017/9/18.
56
*/
67

src/wu/seal/jsontokotlin/Panel.kt

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,9 @@ class PropertyPanel(layout: LayoutManager?, isDoubleBuffered: Boolean) : JPanel(
5151
}
5252

5353

54+
/**
55+
* Comment Config Panel
56+
*/
5457
class CommentConfigPanel(layout: LayoutManager?, isDoubleBuffered: Boolean) : JPanel(layout, isDoubleBuffered) {
5558

5659
constructor(layout: LayoutManager?) : this(layout, false)
@@ -88,7 +91,9 @@ class CommentConfigPanel(layout: LayoutManager?, isDoubleBuffered: Boolean) : JP
8891

8992
}
9093

91-
94+
/**
95+
* Target JsonLib ConfigPanel
96+
*/
9297
class TargetJsonLibConfigPanel(layout: LayoutManager?, isDoubleBuffered: Boolean) : JPanel(layout, isDoubleBuffered) {
9398

9499
constructor(layout: LayoutManager?) : this(layout, false)

src/wu/seal/jsontokotlin/Property.kt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,10 +27,10 @@ class KProperty(val rawPropertyName: String, val propertyType: String, val prope
2727

2828
} else if (ConfigManager.targetJsonConverterLib == TargetJsonConverter.Gson) {
2929

30-
blockBulder.append(GsonSupportor.getGsonSupportorProperty(rawPropertyName, propertyType))
30+
blockBulder.append(GsonSupporter.getGsonSupportorProperty(rawPropertyName, propertyType))
3131
}
3232

33-
if (!ConfigManager.isCommentOff) {
33+
if (!ConfigManager.isCommentOff && propertyValue.isNotBlank()) {
3434
blockBulder.append(" //").append(propertyValue)
3535
}
3636

0 commit comments

Comments
 (0)