0

I have generated a Json in a Scala program using the javax.json and Google gson library.

However what I have managed to accomplish so far (Problem JSON) has problems :

  • I dont need the backslashes.
  • The equivalent_comps element (array) is not formatted properly.

Problem JSON:

   {
    "outcomes": [
       {
         "some_line": "Hampton Court",
         "some_name": "Divya Katdare",
         "equivalent_comps": [
           "{\"comp_type\" : \"SNumber\", \"comp_name\" : \"636-74-1234\"} {\"comp_type\" : \"AENumber\", \"comp_name\" : \"843497127459638\"}{\"comp_type\" : \"VNumber\", \"comp_name\" : \"5111111111111111\"}"
          ]
        }
     ]
   }

What I want to accomplish:

{
"outcomes": [
  {
    "some_line": "Hampton Court",
    "some_name": "Divya Katdare",
    "equivalent_comps": [
       {
         "comp_type" : "SNumber", 
         "comp_name" : "636-74-1234"
      },
     {
        "comp_type" :  "AENumber", 
        "comp_name" : "843497127459638"
    },
    {
        "comp_type" : "VNumber", 
        "comp_name" : "5111111111111111"
      }
    ]
  }
]
 }

Here are the steps I took to accomplish my task:

Step 0: Look up similar questions on StackOverflow and Google.

I looked up resources and did my research before I made this post. However I have been unsuccessful even after all the research, trials and errors:

  1. String.replaceAll single backslashes with double backslashes
  2. String replace a Backslash
  3. Why String.ReplaceAll() in java requires 4 slashes "\\\\" in regex to actually replace "\"?
  4. http://www.xyzws.com/javafaq/how-many-backslashes/198

Step 1: Import the required libraries

import javax.json.{JsonValue, Json}
import com.google.gson.{GsonBuilder, JsonParser}

Step 2: Create a StringWriter

var writer = new StringWriter()

Step 3: Create a generator

val generator = Json.createGenerator(writer)

Step 4: Create the initial list that I want to eventually transform to the JSON I want

val componentList = List((SNumber,636-74-1234), (AENumber,843497127459638), (VNumber,5111111111111111))

Step 5: Iterate through the componentList and create a List of JSONObjects

val componentListAsJsonObjectList = 
  for(component <- componentList) 
    yield (scala.util.parsing.json.JSONObject(
      Map("comp_type" -> component._1,"comp_name" -> component._2)
    ))

println("componentListAsJsonObjectList is: " + componentListAsJsonObjectList)

The above println results in the output below:

List({"comp_type" : "SNumber", "comp_name" : "636-74-1234"}, {"comp_type" : "AENumber", "comp_name" : "843497127459638"}, {"comp_type" : "VNumber", "comp_name" : "5111111111111111"})

Step 6: Convert the List of JSONObjects to a string

val componentListAsJsonString = componentListAsJsonObjectList.mkString
println("componentListAsJsonString is: " + componentListAsJsonString)

componentListAsJsonString printed out:

{"comp_type" : "SNumber", "comp_name" : "636-74-1234"}{"comp_type" : "AENumber", "comp_name" : "843497127459638"}{"comp_type" : "VNumber", "comp_name" : "5111111111111111"}

Step 7: Invoke methods on the generator to create my desired JSON with the componentListAsJsonString

generator
  .writeStartObject()
    .writeStartArray("outcomes")
      .writeStartObject()   
        .write("spme_line", "I am fine")
        .write("some_name", "Divya Katdare")   
        .writeStartArray("equivalent_comps")   
          .write(componentListAsJsonString)
        .writeEnd()
      .writeEnd()
    .writeEnd()
  .writeEnd()

Step 8: Close the generator

generator.close()

Step 9: Prettify the JSON using the gson's JsonParser

val prettyJson = makeJsonPretty(writer.toString.trim)

def makeJsonPretty(generatedJson: String): String = {
  val parser = new JsonParser()
  val json = parser.parse(generatedJson).getAsJsonObject
  val prettyGson = new GsonBuilder().setPrettyPrinting().create()
  val prettyJson = prettyGson.toJson(json)
  prettyJson
}

Step 10: Inspect the JSON created and compare it with the desired JSON format

println("\nPretty JSON Result:\n" + prettyJson)

This outputs the Problem Json at the beginning of my question.

Finally I create the Json I have wanted all along. However it has all those backslashes in it.

Step 11: I validated the JSON

It checks out to be valid Json, even though it is not what I would like it be.

Any suggestions or help needed to fix this JSON is appreciated.

Community
  • 1
  • 1
user3825558
  • 585
  • 1
  • 8
  • 24

1 Answers1

1

Are you bound to javax.json? There are a lot of scala libraries for json without such side effects. Just for example:

import org.json4s._
import org.json4s.jackson.JsonMethods._
import org.json4s.jackson.Serialization.write
implicit val format = DefaultFormats

case class Comp(comp_type: String, comp_name: String)
case class Outcome(some_line: String, some_name: String, equivalent_comps: List[Comp])
case class A(outcomes: List[Outcome])
val componentList = List(
  Comp("SNumber","636-74-1234"),
  Comp("AENumber","843497127459638"),
  Comp("VNumber","5111111111111111")
)
val oc = Outcome("Hampton Court", "Divya Katdare", componentList)
val a = A(List(oc))
pretty(parse(write(a)))

and result:

res0: String = {
  "outcomes" : [ {
    "some_line" : "Hampton Court",
    "some_name" : "Divya Katdare",
    "equivalent_comps" : [ {
      "comp_type" : "SNumber",
      "comp_name" : "636-74-1234"
    }, {
      "comp_type" : "AENumber",
      "comp_name" : "843497127459638"
    }, {
      "comp_type" : "VNumber",
      "comp_name" : "5111111111111111"
    } ]
  } ]
}
Zernike
  • 1,758
  • 1
  • 16
  • 26