0

I am newto the scala language to i am trying to read the json file in my scala file using jackson library

my son file is like this

{
  "Rice":[
    {
      "name":"Basmati",
      "price":40
    },
    {
      "name":"jeera",
      "price":30
    },
    {
      "name":"Indrayani",
      "price":40
    }
  ],
  "Pulses":[
    {
      "name":"peas",
      "price":60
    },
    {
      "name":"ground nut",
      "price":60
    },
    {
      "name":"dal",
      "price":80
    }
  ],
  "Wheats":[
    {
      "name":"atta",
      "price":40
    },
    {
      "name":"bread",
      "price":45
    },
    {
      "name":"bun",
      "price":50
    }
  ]
}

I tried with the case classes to store and print the data code sample like this

case class Inventory(var name:String,var price:String)

object InventoryDataManagement {
  def main(args: Array[String]): Unit = {
    val mapper = JsonMapper.builder()
      .addModule(DefaultScalaModule)
      .build()

    val src = new File("src/main/json/inventary.json")

    val myMap = mapper.readValue(src,classOf[Inventory])

    println(myMap.name)
  }
}

but I am getting error like below

Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "Rice" (class Inventory), not marked as ignorable (2 known properties: "price", 
"name"])

please help to understand this thanks in advance!!!

1 Answer 1

1

Unrecognized field "Rice" (class Inventory)

This error should make you notice that Jackson is looking for a field Rice on the Inventory class, which doesn't make sense.

Why so?

Because you are telling Jackson to read your JSON file as a single Inventory instance.

This is not what your JSON file contains, it contains something that can be represented as a Map[String, Seq[Inventory]].

You should try something like this instead:

mapper.readValue(src,classOf[Map[String, Seq[Inventory]]])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.