Skip to content

Commit 4d16463

Browse files
committed
try to fix unsupport exception
1 parent 5a2e253 commit 4d16463

File tree

7 files changed

+147
-51
lines changed

7 files changed

+147
-51
lines changed

build.gradle

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
buildscript {
2-
ext.kotlin_version = '1.2.31'
2+
ext.kotlin_version = '1.2.51'
33

44
repositories {
55
mavenLocal()

src/main/kotlin/wu/seal/jsontokotlin/KotlinCodeMaker.kt

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -36,10 +36,14 @@ class KotlinCodeMaker {
3636

3737
val jsonElement = inputElement
3838
if (jsonElement!!.isJsonObject) {
39-
appClassName(stringBuilder)
39+
appendClassName(stringBuilder)
4040
appendCodeMember(stringBuilder, jsonElement.asJsonObject)
4141
} else {
42-
throw IllegalArgumentException("UnSupport")
42+
/**
43+
* in this condition the only result it that we just give the json a List<Any> type is enough, No need to
44+
* do any convert to make class type
45+
*/
46+
throw UnSupportJsonException("Unsupported Json String")
4347
}
4448

4549
stringBuilder.append(")")
@@ -77,7 +81,7 @@ class KotlinCodeMaker {
7781
}
7882
}
7983

80-
private fun appClassName(stringBuilder: StringBuilder) {
84+
private fun appendClassName(stringBuilder: StringBuilder) {
8185
val classAnnotation = KClassAnnotation.getClassAnnotation(className.toString())
8286
stringBuilder.append(classAnnotation)
8387
if (classAnnotation.isNotBlank()) stringBuilder.append("\n")
@@ -111,14 +115,12 @@ class KotlinCodeMaker {
111115
if (ConfigManager.enableMapType && maybeJsonObjectBeMapType(jsonElementValue.asJsonObject)) {
112116
val mapKeyType = getMapKeyTypeConvertFromJsonObject(jsonElementValue.asJsonObject)
113117
val mapValueType = getMapValueTypeConvertFromJsonObject(jsonElementValue.asJsonObject)
114-
if (mapValueType == MAP_DEFAULT_OBJECT_VALUE_TYPE
115-
|| mapValueType.contains(MAP_DEFAULT_ARRAY_ITEM_VALUE_TYPE)
116-
) {
118+
if (mapValueIsObjectType(mapValueType)) {
117119
toBeAppend.add(
118-
KotlinCodeMaker(
119-
getChildType(mapValueType),
120-
jsonElementValue.asJsonObject.entrySet().first().value
121-
).makeKotlinData()
120+
KotlinCodeMaker(
121+
getChildType(mapValueType),
122+
jsonElementValue.asJsonObject.entrySet().first().value
123+
).makeKotlinData()
122124
)
123125
}
124126
val mapType = "Map<$mapKeyType,$mapValueType>"
@@ -136,13 +138,16 @@ class KotlinCodeMaker {
136138
}
137139
}
138140

141+
private fun mapValueIsObjectType(mapValueType: String) = (mapValueType == MAP_DEFAULT_OBJECT_VALUE_TYPE
142+
|| mapValueType.contains(MAP_DEFAULT_ARRAY_ITEM_VALUE_TYPE))
143+
139144

140145
private fun addProperty(
141-
stringBuilder: StringBuilder,
142-
property: String,
143-
type: String,
144-
value: String?,
145-
isLast: Boolean = false
146+
stringBuilder: StringBuilder,
147+
property: String,
148+
type: String,
149+
value: String?,
150+
isLast: Boolean = false
146151
) {
147152
var innerValue = value
148153
if (innerValue == null) {
@@ -158,7 +163,7 @@ class KotlinCodeMaker {
158163
val propertyComment = p.getPropertyComment()
159164
if (!ConfigManager.isCommentOff && propertyComment.isNotBlank())
160165
stringBuilder.append(" // ")
161-
.append(getCommentCode(propertyComment))
166+
.append(getCommentCode(propertyComment))
162167
stringBuilder.append("\n")
163168
}
164169

src/main/kotlin/wu/seal/jsontokotlin/MakeKotlinClassAction.kt

Lines changed: 30 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ class MakeKotlinClassAction : AnAction("MakeKotlinClass") {
4242
*/
4343
var tempClassName = ""
4444
val couldGetAndReuseClassNameInCurrentEditFileForInsertCode =
45-
couldGetAndReuseClassNameInCurrentEditFileForInsertCode(editorText)
45+
couldGetAndReuseClassNameInCurrentEditFileForInsertCode(editorText)
4646

4747
if (couldGetAndReuseClassNameInCurrentEditFileForInsertCode) {
4848
/**
@@ -54,9 +54,9 @@ class MakeKotlinClassAction : AnAction("MakeKotlinClass") {
5454
inputDialog.show()
5555
val className = inputDialog.getClassName()
5656
val inputString = inputDialog.inputString
57-
val json = if (inputString?.startsWith("http") == true) {
57+
val json = if (inputString?.startsWith("http") == true) {
5858
URL(inputString).readText()
59-
} else inputString
59+
} else inputString
6060
if (json == null || json.isEmpty()) {
6161
return
6262
}
@@ -75,16 +75,18 @@ class MakeKotlinClassAction : AnAction("MakeKotlinClass") {
7575
}
7676

7777

78+
} catch (e: UnSupportJsonException) {
79+
Messages.showInfoMessage("No need converting, just use List<Any> is enough for your json string", "Tip")
7880
} catch (e: Throwable) {
7981
dealWithException(jsonString, e)
8082
throw e
8183
}
8284
}
8385

8486
private fun reuseClassName(
85-
couldGetAndReuseClassNameInCurrentEditFileForInserCode: Boolean,
86-
className: String,
87-
tempClassName: String
87+
couldGetAndReuseClassNameInCurrentEditFileForInserCode: Boolean,
88+
className: String,
89+
tempClassName: String
8890
) = couldGetAndReuseClassNameInCurrentEditFileForInserCode && className == tempClassName
8991

9092
private fun couldNotInsertCode(editor: Editor?): Boolean {
@@ -108,11 +110,11 @@ class MakeKotlinClassAction : AnAction("MakeKotlinClass") {
108110
}
109111

110112
private fun insertKotlinCode(
111-
project: Project?,
112-
document: Document,
113-
className: String,
114-
jsonString: String,
115-
caret: Caret?
113+
project: Project?,
114+
document: Document,
115+
className: String,
116+
jsonString: String,
117+
caret: Caret?
116118
): Boolean {
117119
ImportClassWriter.insertImportClassCode(project, document)
118120

@@ -138,8 +140,8 @@ class MakeKotlinClassAction : AnAction("MakeKotlinClass") {
138140
offset = document.textLength
139141
}
140142
document.insertString(
141-
Math.max(offset, 0),
142-
ClassCodeFilter.removeDuplicateClassCode(codeMaker.makeKotlinDataClassCode())
143+
Math.max(offset, 0),
144+
ClassCodeFilter.removeDuplicateClassCode(codeMaker.makeKotlinDataClassCode())
143145
)
144146
}
145147
return true
@@ -153,12 +155,12 @@ class MakeKotlinClassAction : AnAction("MakeKotlinClass") {
153155
fun getCleanText(editorText: String): String {
154156
val tempCleanText = editorText.substringBeforeLast("class")
155157
val cleanText =
156-
if (tempCleanText.trim().endsWith("data")) tempCleanText.trim().removeSuffix("data") else tempCleanText
158+
if (tempCleanText.trim().endsWith("data")) tempCleanText.trim().removeSuffix("data") else tempCleanText
157159
return cleanText
158160
}
159161

160162
fun getCurrentEditFileTemClassName(editorText: String) = editorText.substringAfterLast("class")
161-
.substringBefore("(").substringBefore("{").trim()
163+
.substringBefore("(").substringBefore("{").trim()
162164

163165
/**
164166
* whether we could reuse current class name declared in the edit file for inserting data class code
@@ -169,20 +171,20 @@ class MakeKotlinClassAction : AnAction("MakeKotlinClass") {
169171
var couldGetAndReuseClassNameInCurrentEditFileForInsertCode = false
170172
val removeDocComment = editorText.replace(Regex("/\\*\\*(.|\n)*\\*/", RegexOption.MULTILINE), "")
171173
val removeDocCommentAndPackageDeclareText = removeDocComment
172-
.replace(Regex("^(?:\\s*package |\\s*import ).*$", RegexOption.MULTILINE), "")
174+
.replace(Regex("^(?:\\s*package |\\s*import ).*$", RegexOption.MULTILINE), "")
173175
if ((removeDocCommentAndPackageDeclareText.indexOf("class") == removeDocCommentAndPackageDeclareText.lastIndexOf(
174-
"class"
175-
)
176-
&& removeDocCommentAndPackageDeclareText.indexOf("class") != -1
177-
&& removeDocCommentAndPackageDeclareText.substringAfter("class").contains("(").not()
178-
&& removeDocCommentAndPackageDeclareText.substringAfter("class").contains(":").not()
179-
&& removeDocCommentAndPackageDeclareText.substringAfter("class").contains("=").not())
180-
|| (removeDocCommentAndPackageDeclareText.indexOf("class") == removeDocCommentAndPackageDeclareText.lastIndexOf(
181-
"class"
182-
)
183-
&& removeDocCommentAndPackageDeclareText.indexOf("class") != -1
184-
&& removeDocCommentAndPackageDeclareText.substringAfter("class").substringAfter("(")
185-
.replace(Regex("\\s"), "").let { it.equals(")") || it.equals("){}") })
176+
"class"
177+
)
178+
&& removeDocCommentAndPackageDeclareText.indexOf("class") != -1
179+
&& removeDocCommentAndPackageDeclareText.substringAfter("class").contains("(").not()
180+
&& removeDocCommentAndPackageDeclareText.substringAfter("class").contains(":").not()
181+
&& removeDocCommentAndPackageDeclareText.substringAfter("class").contains("=").not())
182+
|| (removeDocCommentAndPackageDeclareText.indexOf("class") == removeDocCommentAndPackageDeclareText.lastIndexOf(
183+
"class"
184+
)
185+
&& removeDocCommentAndPackageDeclareText.indexOf("class") != -1
186+
&& removeDocCommentAndPackageDeclareText.substringAfter("class").substringAfter("(")
187+
.replace(Regex("\\s"), "").let { it.equals(")") || it.equals("){}") })
186188
) {
187189
couldGetAndReuseClassNameInCurrentEditFileForInsertCode = true
188190
}

src/main/kotlin/wu/seal/jsontokotlin/TargetJsonElement.kt

Lines changed: 57 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,10 @@ package wu.seal.jsontokotlin
33
import com.google.gson.*
44
import java.util.*
55

6-
6+
/**
7+
* This class aim at filtering out the expected Json Element to be convert from Json array
8+
*
9+
*/
710
class TargetJsonElement : ITargetJsonElement {
811
private val jsonElement: JsonElement
912

@@ -17,16 +20,65 @@ class TargetJsonElement : ITargetJsonElement {
1720

1821
override fun getTargetJsonElementForGeneratingCode(): JsonElement {
1922
if (this.jsonElement.isJsonArray) {
20-
val jsonElementNotArray = getArrayChildElement(this.jsonElement.asJsonArray)
21-
if (jsonElementNotArray.isJsonObject) {
22-
return jsonElementNotArray
23+
if (jsonElement.asJsonArray.size() == 0) {
24+
return gson.toJsonTree(Any())
25+
} else if (allElementAreObject(jsonElement.asJsonArray)) {
26+
val jsonElementNotArray = getArrayChildElement(this.jsonElement.asJsonArray)
27+
if (jsonElementNotArray.isJsonObject) {
28+
return jsonElementNotArray
29+
} else {
30+
throw IllegalStateException("Unbelievable! should not throw out this exception")
31+
}
32+
} else if (allElementAreSamePrimitiveType(jsonElement.asJsonArray)) {
33+
return jsonElement.asJsonArray[0]
34+
} else {
35+
return gson.toJsonTree(Any())
2336
}
2437
} else if (this.jsonElement.isJsonObject) {
2538
return this.jsonElement
39+
} else if (this.jsonElement.isJsonPrimitive) {
40+
return this.jsonElement
41+
} else {
42+
return this.jsonElement
2643
}
27-
throw IllegalFormatFlagsException("Unsupported Json String")
2844
}
2945

46+
private fun allElementAreObject(jsonArray: JsonArray): Boolean {
47+
var allElementAreObject = true
48+
jsonArray.forEach {
49+
if (it.isJsonObject.not()) {
50+
allElementAreObject = false
51+
return@forEach
52+
}
53+
}
54+
return allElementAreObject
55+
}
56+
57+
private fun allElementAreSamePrimitiveType(jsonArray: JsonArray): Boolean {
58+
var allElementAreSamePrimitiveType = true
59+
jsonArray.forEach {
60+
if (it.isJsonPrimitive.not()) {
61+
allElementAreSamePrimitiveType = false
62+
return@forEach
63+
}
64+
if (theSamePrimitiveType(jsonArray[0].asJsonPrimitive, it.asJsonPrimitive).not()) {
65+
allElementAreSamePrimitiveType = false
66+
return@forEach
67+
}
68+
}
69+
return allElementAreSamePrimitiveType
70+
}
71+
72+
private fun theSamePrimitiveType(first: JsonPrimitive, second: JsonPrimitive): Boolean {
73+
74+
val sameBoolean = first.isBoolean && second.isBoolean
75+
76+
val sameNumber = first.isNumber && second.isNumber
77+
78+
val sameString = first.isString && second.isString
79+
80+
return sameBoolean || sameNumber || sameString
81+
}
3082

3183
private fun getArrayChildElement(jsonArray: JsonArray): JsonElement {
3284
if (jsonArray.size() >= 1) {
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
package wu.seal.jsontokotlin
2+
3+
4+
/**
5+
* Throw out when the json to be convert don't support by this plugin or no need to convert to any classes
6+
*/
7+
class UnSupportJsonException(message: String = "") : Exception(message)

src/test/kotlin/wu/seal/jsontokotlin/StringTest.kt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,4 +26,4 @@ class StringTest {
2626
val result2 = s.substringBefore("AM")
2727
result2.should.be.equal(s)
2828
}
29-
}
29+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package wu.seal.jsontokotlin.gson
2+
3+
import com.google.gson.Gson
4+
import com.google.gson.JsonElement
5+
import com.winterbe.expekt.should
6+
import org.junit.Test
7+
8+
class TestJsonElement {
9+
10+
private val gson = Gson()
11+
@Test
12+
fun isStringJsonObject() {
13+
val jsonElement = gson.toJsonTree("hello")
14+
jsonElement.isJsonObject.should.be.`false`
15+
}
16+
17+
@Test
18+
fun isObjectStringPropertyIsJsonObject() {
19+
val json = """{a:"hello"}"""
20+
val jsonObject = gson.fromJson<JsonElement>(json, JsonElement::class.java)
21+
jsonObject.asJsonObject.get("a").isJsonObject.should.be.`false`
22+
}
23+
24+
@Test
25+
fun isJsonStringArrayElementIsJsonObject() {
26+
val json = """["hello","yes"]"""
27+
val jsonObject = gson.fromJson<JsonElement>(json, JsonElement::class.java)
28+
jsonObject.asJsonArray[0].isJsonObject.should.be.`false`
29+
}
30+
}

0 commit comments

Comments
 (0)