Updated April 10, 2023
Introduction to Kotlin JSON
The kotlin JSON is one of the default methods for parsing the data between the server and client. It is minimal, textual and a subset of JavaScript. It looks like the alternative to XML parsing. The JSON object have contains keys and value pairs which is similar to the map collections. The keys may be of string types and the values are in the JSON types the comma separator is the delimiter for the keys and values the curly braces {} is the operator which represents the JSON object for utilizing the user data which looks like an array that has been bound with the help of array list.
Syntax
In kotlin language is used to implement and combined with other features like JSON, XML, etc. The conversion and parsing of the user data by using the JSON concepts which helps to convert the JSON to data class from the string data type.
data class name1
{
var varibalename: datatype;
}
fun main()
{
val varname= Gson().fromJson<name1>(json,name1::class.java)
val xmlinputs="<xml tag codes>" // depends upon the requirement
val varnames=XML.toJSONObject(xmlinputs)
---- some kotlin logic codes depends upon the requirement--
}
The above code is the basic syntax for utilizing the JSON concept in the kotlin language. We used Gson() method for to call the fromJson() method in the kotlin interface.
How does JSON works in Kotlin?
The JSON is the JavaScript object notation with the help of this the user data are parsed between the client and server. it is easier to read and fast the data to parse and refresh it. In kotlin more concise for the immutable data classes and it makes it easy to build the basic model for the JSON data formats. The user data are filed accordingly on the required classes that will be used to implement with the other default methods that are it not supported the boilerplate codes. In default values will fill in the gaps when decoding JSON data from the network tools like post-man etc. The request will be sent with any of the tools and we received the response in the JSON format according to the request raised from the user end. With the help of streaming API, we can handle the huge set of JSON documents by reading from the stream this feature will allow for our code to process JSON values while it is still accepted as the read value formats. The JSON object is the modifiable set of name and value mappings the names are unique and non-null string values it may be the mix of JSON Objects, JSON arrays, strings, and other data types, etc.
Examples of Kotlin JSON
Let us discuss examples of Kotlin JSON.
Example #1
Code:
package one;
import org.json.JSONObject
import org.json.XML
fun main(args: Array<String>) {
val firsts = 14
val inputxml = """
<?xml version="1.0" encoding="UTF-8"?>
<ImportConfig>
<ImportNodes Type="Order" UniqueId="OrderID+SKU+Door"
Path="C:\Import\PO.csv"
Log="detail"
Delimiter=";">
<Attribute Id="RealizedProduct" DestType="SKU" SourceId="POSKUURL" Url="true" CallParameter="FromURL" AbortIfMissing="true" OnCreate="true" />
<Attribute Id="PO" Url="true" CallParameter="ParentURL" AbortIfMissing="true" OnCreate="true" />
</ImportNodes>
</ImportConfig>
<Reader Type="SQLServer" Database="PurchaseOrders" Instance="MBI-UAT" User="sa" Password="csisa"/>
<Query Query="SELECT REPLACE((CONCAT(POSupplier, SalesOrder, CitesCode)), ' ', '') AS 'PO', REPLACE((CONCAT(S.SalesOrder, S.Door, POSupplier)), ' ', '') AS 'OrderID', REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(UPPER(CONCAT(S.Season,S.ProductID)),' ', ''),'-', ''),'(', ''),')', ''),'.', ''),'_','') AS 'SKU',URL.NodeURL AS 'POSKUURL',CONCAT(S.SalesOrder, '-', S.Door) AS 'SalesOrder',S.POSupplier,S.ConsolidatedQty,S.Buyer,S.Seller,S.Door FROM [PurchaseOrders].[dbo].SalesOrderLine S CROSS APPLY (SELECT TOP 1 U.NodeURL FROM C8.Shadow.Shadow_POSKU U WHERE U.NewPOImpID COLLATE DATABASE_DEFAULT = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(UPPER(CONCAT(S.Season,S.StyleTN,S.Colorway)),' ', ''),'-', ''),'(', ''),')', ''),'.', ''),'_','') COLLATE DATABASE_DEFAULT) URL"/>
<Attribute Id="OrderQuote" DestType="SupplierItem" Expr='block(cn=POColor.ProductColor.`Node Name`,sup=PO.POSupplier.SupplierNumber,quotes=POProduct.Product.ProductSourcing.join(ProductSources).join(SupplierItems).join(CurrentRevision),out=list(ref_type),fn=list(ref_type),foreach(rec1,quotes,block(cols=rec1.Colors,foreach(rec2,cols,if(rec2.`Node Name`==cn,add(out,rec1),"")))),lst=out.filter(State.enumValue()=="APPROVED"||State.enumValue()=="DRAFT" ||State.enumValue()=="PENDING").filter(Master.__Parent__.Supplier.SupplierNumber==sup),foreach(rec,lst,add(fn,rec.Master)),if(fn.size() == 1, at(fn, 0), dummy))'/>
<Attribute Id="QuantityPerSize" SourceId="ConsolidatedQty" ValueOp="Replace" />
<Attribute Id="MBI_Order_Buyer_Ref" SourceId="Buyer" RefUniqueId="Node Name" />
<Attribute Id="MBI_Order_Seller_Ref" SourceId="Seller" RefUniqueId="Node Name" />
<Attribute Id="MBI_Order_Door_Ref" SourceId="Door" RefUniqueId="MBI_Contact_ContactID_String" />
<Attribute Id="MBI_Order_SalesOrder_Ref" SourceId="SalesOrder" RefUniqueId="Node Name" />
"""
val jsonconversion = XML.toJSONObject(inputxml)
val result = jsonconversion.toString(firsts)
println(result)
}
Sample Output:
In the first example, we can convert the XML data to JSON format data.
Example #2
Code:
package one;
import org.json.JSONObject
import org.json.XML
fun main(args: Array<String>) {
val inputxml = """
{
"item": 101700111,
"dept": 69,
"class": 1314,
"subclass": 1051,
"item_desc": "Saleigh's Groove",
"short_desc": "Saleigh's Groove",
"up_desc": "SALEIGH'S GROOVE",
"cost_zone_group_id": 2000,
"package_size": 6,
"mfg_rec_retail": 349.99,
"supplier": "BPS-004289",
"vpn": 786431,
"selling_unit_retail": 349.99,
"origin_country_id": "ZA",
"unit_cost": 125.00,
"purchase_type": 0,
"image_name": "526_small.jpg",
"image_addr": "http://cuplmcpt01/plm/",
"PriceZones":{"1000":456,
"1001":456,
"1002":456,},
"last_update_id":"SalWag",
"vat_code": "IVT",
"UDA": [
{"uda_id": 1, "uda_value": 1, "uda_desc": "Brand","uda_value_desc":"K-Way"},
{"uda_id": 21,"uda_value": 2, "uda_desc": "Story","uda_value_desc":"Some Story"},
{"uda_id": 44,"uda_value": 12,"uda_desc": "Bonded", "uda_value_desc":"No"},
{"uda_id": 41,"uda_value": 10,"uda_desc": "Uniform","uda_value_desc":"No"}] }
"""
val jsonconversion = JSONObject(inputxml)
val result = XML.toString(jsonconversion)
println(result)
}
Sample Output:
In the Second example, we can convert the JSON file data to the XML format by using the default methods. We can call the XML .toString() method to convert the JSON data to the string format and XML format.
Example #3
Code:
package one;
import java.io.File
import org.json.JSONObject
import org.json.XML
import com.google.gson.Gson
import com.google.gson.GsonBuilder
fun main(args: Array<String>) {
val firsts = 7
val inputxml = """
<?xml version="1.0" encoding="UTF-8"?>
<?xml version="1.0" encoding="UTF-8"?>
<ImportConfig>
<ImportNodes Type="Order" UniqueId="OrderID+SKU+Door"
Path="C:\Import\PO.csv"
Log="detail"
Delimiter=";">
<Attribute Id="RealizedProduct" DestType="SKU" SourceId="POSKUURL" Url="true" CallParameter="FromURL" AbortIfMissing="true" OnCreate="true" />
<Attribute Id="PO" Url="true" CallParameter="ParentURL" AbortIfMissing="true" OnCreate="true" />
</ImportNodes>
</ImportConfig>
<Reader Type="SQLServer" Database="PurchaseOrders" Instance="MBI-UAT" User="sa" Password="csisa"/>
<Query Query="SELECT REPLACE((CONCAT(POSupplier, SalesOrder, CitesCode)), ' ', '') AS 'PO', REPLACE((CONCAT(S.SalesOrder, S.Door, POSupplier)), ' ', '') AS 'OrderID', REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(UPPER(CONCAT(S.Season,S.ProductID)),' ', ''),'-', ''),'(', ''),')', ''),'.', ''),'_','') AS 'SKU',URL.NodeURL AS 'POSKUURL',CONCAT(S.SalesOrder, '-', S.Door) AS 'SalesOrder',S.POSupplier,S.ConsolidatedQty,S.Buyer,S.Seller,S.Door FROM [PurchaseOrders].[dbo].SalesOrderLine S CROSS APPLY (SELECT TOP 1 U.NodeURL FROM C8.Shadow.Shadow_POSKU U WHERE U.NewPOImpID COLLATE DATABASE_DEFAULT = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(UPPER(CONCAT(S.Season,S.StyleTN,S.Colorway)),' ', ''),'-', ''),'(', ''),')', ''),'.', ''),'_','') COLLATE DATABASE_DEFAULT) URL"/>
<Attribute Id="OrderQuote" DestType="SupplierItem" Expr='block(cn=POColor.ProductColor.`Node Name`,sup=PO.POSupplier.SupplierNumber,quotes=POProduct.Product.ProductSourcing.join(ProductSources).join(SupplierItems).join(CurrentRevision),out=list(ref_type),fn=list(ref_type),foreach(rec1,quotes,block(cols=rec1.Colors,foreach(rec2,cols,if(rec2.`Node Name`==cn,add(out,rec1),"")))),lst=out.filter(State.enumValue()=="APPROVED"||State.enumValue()=="DRAFT" ||State.enumValue()=="PENDING").filter(Master.__Parent__.Supplier.SupplierNumber==sup),foreach(rec,lst,add(fn,rec.Master)),if(fn.size() == 1, at(fn, 0), dummy))'/>
<Attribute Id="QuantityPerSize" SourceId="ConsolidatedQty" ValueOp="Replace" />
<Attribute Id="MBI_Order_Buyer_Ref" SourceId="Buyer" RefUniqueId="Node Name" />
<Attribute Id="MBI_Order_Seller_Ref" SourceId="Seller" RefUniqueId="Node Name" />
<Attribute Id="MBI_Order_Door_Ref" SourceId="Door" RefUniqueId="MBI_Contact_ContactID_String" />
<Attribute Id="MBI_Order_SalesOrder_Ref" SourceId="SalesOrder" RefUniqueId="Node Name" />
"""
val jsonconversion = XML.toJSONObject(inputxml)
val result = jsonconversion.toString(firsts)
println(result)
val gs=Gson()
var news:String=gs.toJson(result)
File("output.json").writeText(news)
}
Sample Output:
In the above final example, we can convert the XML to JSON and it will write the data to a separate JSON file.
Conclusion
In the kotlin language, we can use different features and plugins to create an application with user-friendly nature. Among these JSON is one of the data formats with user -convenience and it can be used to send and receive the user response through a web-based application like kotlin.
Recommended Articles
This is a guide to Kotlin JSON. Here we discuss the introduction, syntax, and working of JSON in Kotlin along with different examples and its code implementation. You may also have a look at the following articles to learn more –