6

For example, I have a JSON format like this:

{"class":"MySpecialClass", "attri1":"value1", "attri2":"value2"}

I would like to create a Object, which is a MySpecialClass Object, and get two attribute, attri1 and attri2 with the value of value1 and value2.

Here is the requirement:

  1. I have a class file, named, MySpecialClass, and have attri1, and attri2, can I create this object, and assign the value in this?

  2. I DONT'T have the class file MySpecialClass, I would like to generate it on the runtime, is this possible to do so? Thanks.

DNB5brims
  • 29,344
  • 50
  • 131
  • 195
  • 2
    Possible duplicate of http://stackoverflow.com/questions/1395551/convert-a-json-string-to-object-in-java – Zéychin Aug 03 '12 at 08:48

3 Answers3

3

Your first case is perfectly feasible using any Java/JSON parser.

Your second case is possible, but hard work.

You can construct classes at runtime using bytecode engineering - e.g. using Apache BCEL. Note that the JSON will contail fields only, and not behaviour nor type.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
1

Take a look at https://github.com/google/gson it does what you want

Cœur
  • 37,241
  • 25
  • 195
  • 267
fmsf
  • 36,317
  • 49
  • 147
  • 195
0

You want a JSON processor, like Jackson. I'm not sure you can easily do your second case this way, for that you may be best looking at a JVM JavaScript implementation unless you want to get into stuff like on the fly bytecode manipulation. There's one in the Java6 runtime.

brabster
  • 42,504
  • 27
  • 146
  • 186