Deserializing json with various keys as value - java

I have json like:
{"avatars": {
"1": "value",
"2":"value",
"900":"value"
}
}
And my model:
class Response{
List<Avatar> avatars;
}
class Avatar{
String id;
String value;
}
How do I properly parse the Json using Jackson

You should use json like this to automaticaly parse:
{"avatars": [
{"id": "1", "value": "someValue1"},
{"id": "2", "value": "someValue2"},
{"id": "300", "value": "someValue300"},
]
}
or write custom parser for Jackson.

Try this:
Using Java JSON library
public class Test {
public static void main(String[] args) {
Response response = new Response();
Serializer.serialize("{\"avatars\": { \"1\": \"value\", \"2\":\"value\", \"900\":\"value\" }}", response);
System.out.println(response.toString());
}
}
class Serializer {
public static void serialize(String j, Response response) {
try {
JSONObject json = new JSONObject(j).getJSONObject("avatars");
Iterator keys = json.keys();
while (keys.hasNext()) {
String id = keys.next().toString();
String value = json.getString(id);
response.addAvatar(id, value);
}
} catch (JSONException ignore) {
}
}
}
/**
* This is a response class
*/
class Response {
List<Avatar> avatars;
public Response() {
/**
* You can use LinkedList, I think it's the best way.
*/
this.avatars = new LinkedList<Avatar>();
}
public void addAvatar(String id, String value) {
this.avatars.add(new Avatar(id, value));
}
public String toString() {
String result = "";
for (Avatar avatar : this.avatars) {
result += (result.length() == 0 ? "" : ", ") + "[" + avatar.getId() + "=" + avatar.getValue() + "]";
}
return result;
}
}
/**
* This is an avatar class
*/
class Avatar {
private String id;
private String value;
public Avatar(String id, String value) {
this.id = id;
this.value = value;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
Hope this helps!

You can just use a converter, which avoids the complexity of a full custom deserializer:
#JsonDeserialize(converter = AvatarMapConverter.class)
public List<Avatar> avatars;
The converter needs to declare that it can accept some other type that Jackson can deserialize to, and produce a List<Avatar>. Extending StdConverter will do the plumbing for you:
public class AvatarMapConverter extends StdConverter<Map<String, String>, List<Avatar>> {
#Override
public List<Avatar> convert(Map<String, String> input) {
List<Avatar> output = new ArrayList<>(input.size());
input.forEach((id, value) -> output.add(new Avatar(id, value)));
return output;
}
}
If you need to serialize too, you can write a converter to go the other way and reference that from a #JsonSerialize annotation.

Related

JSON serialize to a different value

I have the below json which im serializing
{
"name":"John",
"switch":"1"
},
{
"name":"Jim",
"switch":"0"
}
I want to serialize it to a differnt name So I had to do it like below
class Data {
private String name;
private String flag;
#JsonProperty("flag")
public byte getFlag() {
return flag;
}
#JsonProperty("switch")
public void setSwitch(String s) {
this.flag = flag;
}
}
So that I get it converted as below
{
"name":"John",
"flag":"1"
},
{
"name":"Jim",
"flag":"0"
}
Now I wanted to map the numic values to Y and N for 1 and 0 respectively. Can I acheive that ?
Im expecting my final string to be like this
{
"name":"John",
"switch":"Y"
},
{
"name":"Jim",
"switch":"N"
}
I agree with #Gaël J, but still if you want to go ahead this code change might help you to convert that 1/0 to Y/N.
public class Application {
#ToString
static class Input {
#JsonProperty("name")
private String name;
#JsonProperty("switch")
private String flag;
#JsonProperty("name")
public void setName(String name){
this.name = name;
}
#JsonProperty("switch")
public void setSwitch(String s) {
for(SwitchMap valuePair : SwitchMap.values()){
if(valuePair.getValue().equals(s)){
this.flag = valuePair.name();
}
}
}
}
public static void main(String[] args) throws JsonProcessingException {
String json = "{\n" +
"\"name\":\"John\",\n" +
"\"switch\":\"1\"\n" +
"}";
ObjectMapper mapper = new ObjectMapper();
Input in = mapper.readValue(json, Input.class);
System.out.println(mapper.writeValueAsString(in));
}
}
define an enum with the mapping
#Getter
public enum SwitchMap {
Y("1"),
N("0");
private final String value;
private SwitchMap(String value){
this.value = value;
}
}

Unable to parse JSON with Jackson (mapping doesn't work)

I am trying to use Jackson to parse sample json as demonstrated below. However, I the parsing doesn't work (fails without any exceptions - as I get an empty string for event.getAccountId(); What could I be doing wrong?
Thanks!
ObjectMapper om = new ObjectMapper();
String json = "{\"_procurementEvent\" : [{ \"accountId\" : \"3243234\",\"procurementType\" : \"view\"," +
"\"_procurementSubType\" : \"Standard Connector\",\"_quantity\" : \"4\", \"_pricePerMonth\" : \"100.00\"" +
",\"_annualPrice\" : \"1200.00\"}]}";
ProcurementEvent event = om.readValue(json, ProcurementEvent.class);
event.getAccountId(); // returns null
#JsonIgnoreProperties(ignoreUnknown = true)
private static class ProcurementEvent {
private String _accountId;
private String _procurementType;
private String _quantity;
private String _pricePerMonth;
private String _annualPrice;
#JsonProperty("accountId")
public String getAccountId() {
return _accountId;
}
public void setAccountId(String accountId) {
_accountId = accountId;
}
#JsonProperty("procurementType")
public String getProcurementType() {
return _procurementType;
}
public void setProcurementType(String procurementType) {
_procurementType = procurementType;
}
#JsonProperty("_quantity")
public String getQuantity() {
return _quantity;
}
public void setQuantity(String quantity) {
_quantity = quantity;
}
#JsonProperty("_pricePerMonth")
public String getPricePerMonth() {
return _pricePerMonth;
}
public void setPricePerMonth(String pricePerMonth) {
_pricePerMonth = pricePerMonth;
}
#JsonProperty("_annualPrice")
public String getAnnualPrice() {
return _annualPrice;
}
public void setAnnualPrice(String annualPrice) {
_annualPrice = annualPrice;
}
}
In the question, try the following approach:
class ProcurementEvents {
private List<ProcurementEvent> _procurementEvent; // + annotations like #JsonIgnoreProperties, getters/ setters, etc.
}
// json from your example
ProcurementEvents events = om.readValue(json, ProcurementEvents.class);
events.get(0).getAccountId();

Converting JSONArray to List<Object>?

I'm trying deserializes a JSONArray to List. To do it I'm trying use Gson but I can't understand why doesn't works and all values of JSON are null.
How could I do this ?
JSON
{ "result" : [
{ "Noticia" : {
"created" : "2015-08-20 19:58:49",
"descricao" : "tttttt",
"id" : "19",
"image" : null,
"titulo" : "ddddd",
"usuario" : "FERNANDO PAIVA"
} },
{ "Noticia" : {
"created" : "2015-08-20 19:59:57",
"descricao" : "hhhhhhhh",
"id" : "20",
"image" : "logo.png",
"titulo" : "TITULO DA NOTICIA",
"usuario" : "FERNANDO PAIVA"
} }
] }
Deserializes
List<Noticia> lista = new ArrayList<Noticia>();
Gson gson = new Gson();
JSONArray array = obj.getJSONArray("result");
Type listType = new TypeToken<List<Noticia>>() {}.getType();
lista = gson.fromJson(array.toString(), listType);
//testing - size = 2 but value Titulo is null
Log.i("LISTSIZE->", lista.size() +"");
for(Noticia n:lista){
Log.i("TITULO", n.getTitulo());
}
Class Noticia
public class Noticia implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String titulo;
private String descricao;
private String usuario;
private Date created;
private String image;
There are two problems with your code :
First is that you are using a getJsonArray() to get the array,
which isn't part of Gson library, you need to use
getAsJsonArray() method instead.
Second is that you are using array.toString() which isn't obvious
because for the fromJson method you need a jsonArray as
parameter and not String and that will cause you parse problems, just remove it.
And use the following code to convert your jsonArray to List<Noticia> :
Type type = new TypeToken<List<Noticia>>() {}.getType();
List<Noticia> lista = gson.fromJson(array, type);
And your whole code will be:
Gson gson = new Gson();
JSONArray array = obj.getAsJsonArray("result");
Type type = new TypeToken<List<Noticia>>() {}.getType();
List<Noticia> lista = gson.fromJson(array, type);
//testing - size = 2 but value Titulo is null
Log.i("LISTSIZE->", lista.size() +"");
for(Noticia n:lista){
Log.i("TITULO", n.getTitulo());
}
I think the problem could be something to do with toString() on JSONArray. But are you using obj.getAsJsonArray method?
Try this:
JSONArray arr = obj.getAsJsonArray("result");
Type listType = new TypeToken<List<Noticia>>() {
}.getType();
return new Gson().fromJson(arr , listType);
Noticia.java
public class Noticia {
private String created;
private String descricao;
private String id;
private String image;
private String titulo;
private String usuario;
public String getCreated() {
return created;
}
public void setCreated(String created) {
this.created = created;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public String getUsuario() {
return usuario;
}
public void setUsuario(String usuario) {
this.usuario = usuario;
}
#Override
public String toString() {
return "Noticia [created=" + created + ", descricao=" + descricao
+ ", id=" + id + ", image=" + image + ", titulo=" + titulo
+ ", usuario=" + usuario + "]";
}
}
Result.java
public class Result {
private Noticia Noticia;
public Noticia getNoticia() {
return Noticia;
}
public void setNoticia(Noticia noticia) {
Noticia = noticia;
}
#Override
public String toString() {
return "Result [Noticia=" + Noticia + "]";
}
}
Item.java
import java.util.List;
public class Item {
private List<Result> result;
public List<Result> getResult() {
return result;
}
public void setResult(List<Result> result) {
this.result = result;
}
#Override
public String toString() {
return "Item [result=" + result + "]";
}
}
Main.java
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.testgson.beans.Item;
public class Main {
private static Gson gson;
static {
gson = new GsonBuilder().create();
}
public static void main(String[] args) {
String j = "{\"result\":[{\"Noticia\":{\"created\":\"2015-08-20 19:58:49\",\"descricao\":\"tttttt\",\"id\":\"19\",\"image\":null,\"titulo\":\"ddddd\",\"usuario\":\"FERNANDO PAIVA\"}},{\"Noticia\":{\"created\":\"2015-08-20 19:59:57\",\"descricao\":\"hhhhhhhh\",\"id\":\"20\",\"image\":\"logo.png\",\"titulo\":\"TITULO DA NOTICIA\",\"usuario\":\"FERNANDO PAIVA\"}}]}";
Item r = gson.fromJson(j, Item.class);
System.out.println(r);
}
}
Final result
Item [result=[Result [Noticia=Noticia [created=2015-08-20 19:58:49, descricao=tttttt, id=19, image=null, titulo=ddddd, usuario=FERNANDO PAIVA]], Result [Noticia=Noticia [created=2015-08-20 19:59:57, descricao=hhhhhhhh, id=20, image=logo.png, titulo=TITULO DA NOTICIA, usuario=FERNANDO PAIVA]]]]
You parse json, that looks like
{ "result" : [
{
"created" : "2015-08-20 19:58:49",
"descricao" : "tttttt",
"id" : "19",
"image" : null,
"titulo" : "ddddd",
"usuario" : "FERNANDO PAIVA"
},
{
"created" : "2015-08-20 19:59:57",
"descricao" : "hhhhhhhh",
"id" : "20",
"image" : "logo.png",
"titulo" : "TITULO DA NOTICIA",
"usuario" : "FERNANDO PAIVA"
}
] }
You need to make another object Item and parse a list of them.
public class Item{
Noticia noticia;
}
Or you can interate through JSONArray, get field "noticia" from each then parse Noticia object from given JSONObject.
Kotlin Ex :
we getting response in form of JSONArry
call.enqueue(object : Callback<JsonArray> {
override fun onResponse(call: Call<JsonArray>, response: Response<JsonArray>) {
val list = response.body().toString()
val gson = Gson()
val obj: CitiesList? = gson.fromJson(list, CitiesList::class.java)
cityLiveData.value = obj!!
}
override fun onFailure(call: Call<JsonArray>, t: Throwable) {
}
})
Here CitiesList CitiesList::class.java is the ArrayList of Cities object
class CitiesList : ArrayList<CitiesListItem>()
Before using GSON add dependancey in Gradle
dependencies {
implementation 'com.google.code.gson:gson:2.8.8'
}

How to access nested elements of json object using getJSONArray method

I have a JSON response that looks like this:
{
"result": {
"map": {
"entry": [
{
"key": { "#xsi.type": "xs:string", "$": "ContentA" },
"value": "fsdf"
},
{
"key": { "#xsi.type": "xs:string", "$": "ContentB" },
"value": "dfdf"
}
]
}
}
}
I want to access the value of the "entry" array object. I am trying to access:
RESPONSE_JSON_OBJECT.getJSONArray("entry");
I am getting JSONException. Can someone please help me get the JSON array from the above JSON response?
You have to decompose the full object to reach the entry array.
Assuming REPONSE_JSON_OBJECT is already a parsed JSONObject.
REPONSE_JSON_OBJECT.getJSONObject("result")
.getJSONObject("map")
.getJSONArray("entry");
Try this code using Gson library and get the things done.
Gson gson = new GsonBuilder().create();
JsonObject job = gson.fromJson(JsonString, JsonObject.class);
JsonElement entry=job.getAsJsonObject("results").getAsJsonObject("map").getAsJsonArray("entry");
String str = entry.toString();
System.out.println(str);
I suggest you to use Gson library. It allows to parse JSON string into object data model. Please, see my example:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;
public class GsonProgram {
public static void main(String... args) {
String response = "{\"result\":{\"map\":{\"entry\":[{\"key\":{\"#xsi.type\":\"xs:string\",\"$\":\"ContentA\"},\"value\":\"fsdf\"},{\"key\":{\"#xsi.type\":\"xs:string\",\"$\":\"ContentB\"},\"value\":\"dfdf\"}]}}}";
Gson gson = new GsonBuilder().serializeNulls().create();
Response res = gson.fromJson(response, Response.class);
System.out.println("Entries: " + res.getResult().getMap().getEntry());
}
}
class Response {
private Result result;
public Result getResult() {
return result;
}
public void setResult(Result result) {
this.result = result;
}
#Override
public String toString() {
return result.toString();
}
}
class Result {
private MapNode map;
public MapNode getMap() {
return map;
}
public void setMap(MapNode map) {
this.map = map;
}
#Override
public String toString() {
return map.toString();
}
}
class MapNode {
List<Entry> entry = new ArrayList<Entry>();
public List<Entry> getEntry() {
return entry;
}
public void setEntry(List<Entry> entry) {
this.entry = entry;
}
#Override
public String toString() {
return Arrays.toString(entry.toArray());
}
}
class Entry {
private Key key;
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Key getKey() {
return key;
}
public void setKey(Key key) {
this.key = key;
}
#Override
public String toString() {
return "[key=" + key + ", value=" + value + "]";
}
}
class Key {
#SerializedName("$")
private String value;
#SerializedName("#xsi.type")
private String type;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
#Override
public String toString() {
return "[value=" + value + ", type=" + type + "]";
}
}
Program output:
Entries: [[key=[value=ContentA, type=xs:string], value=fsdf], [key=[value=ContentB, type=xs:string], value=dfdf]]
If you not familiar with this library, then you can find a lot of informations in "Gson User Guide".
This is for Nikola.
public static JSONObject setProperty(JSONObject js1, String keys, String valueNew) throws JSONException {
String[] keyMain = keys.split("\\.");
for (String keym : keyMain) {
Iterator iterator = js1.keys();
String key = null;
while (iterator.hasNext()) {
key = (String) iterator.next();
if ((js1.optJSONArray(key) == null) && (js1.optJSONObject(key) == null)) {
if ((key.equals(keym)) && (js1.get(key).toString().equals(valueMain))) {
js1.put(key, valueNew);
return js1;
}
}
if (js1.optJSONObject(key) != null) {
if ((key.equals(keym))) {
js1 = js1.getJSONObject(key);
break;
}
}
if (js1.optJSONArray(key) != null) {
JSONArray jArray = js1.getJSONArray(key);
JSONObject j;
for (int i = 0; i < jArray.length(); i++) {
js1 = jArray.getJSONObject(i);
break;
}
}
}
}
return js1;
}
public static void main(String[] args) throws IOException, JSONException {
String text = "{ "key1":{ "key2":{ "key3":{ "key4":[ { "fieldValue":"Empty", "fieldName":"Enter Field Name 1" }, { "fieldValue":"Empty", "fieldName":"Enter Field Name 2" } ] } } } }";
JSONObject json = new JSONObject(text);
setProperty(json, "ke1.key2.key3.key4.fieldValue", "nikola");
System.out.println(json.toString(4));
}
If it's help bro,Do not forget to up for my reputation)))
You can try this:
JSONObject result = new JSONObject("Your string here").getJSONObject("result");
JSONObject map = result.getJSONObject("map");
JSONArray entries= map.getJSONArray("entry");
I hope this helps.
I'm also faced with this issue. So I solved with recursion. Maybe it will be helpfull.
I created method.I used org.json library.
public static JSONObject function(JSONObject obj, String keyMain, String newValue) throws Exception {
// We need to know keys of Jsonobject
Iterator iterator = obj.keys();
String key = null;
while (iterator.hasNext()) {
key = (String) iterator.next();
// if object is just string we change value in key
if ((obj.optJSONArray(key)==null) && (obj.optJSONObject(key)==null)) {
if ((key.equals(keyMain)) && (obj.get(key).toString().equals(valueMain))) {
// put new value
obj.put(key, newValue);
return obj;
}
}
// if it's jsonobject
if (obj.optJSONObject(key) != null) {
function(obj.getJSONObject(key), keyMain, valueMain, newValue);
}
// if it's jsonarray
if (obj.optJSONArray(key) != null) {
JSONArray jArray = obj.getJSONArray(key);
for (int i=0;i<jArray.length();i++) {
function(jArray.getJSONObject(i), keyMain, valueMain, newValue);
}
}
}
return obj;
}
if you have questions, I can explain...
I would also try it this way
1) Create the Java Beans from the JSON schema
2) Use JSON parser libraries to avoid any sort of exception
3) Cast the parse result to the Java object that was created from the initial JSON schema.
Below is an example JSON Schema"
{
"USD" : {"15m" : 478.68, "last" : 478.68, "buy" : 478.55, "sell" : 478.68, "symbol" : "$"},
"JPY" : {"15m" : 51033.99, "last" : 51033.99, "buy" : 51020.13, "sell" : 51033.99, "symbol" : "¥"},
}
Code
public class Container {
private JPY JPY;
private USD USD;
public JPY getJPY ()
{
return JPY;
}
public void setJPY (JPY JPY)
{
this.JPY = JPY;
}
public USD getUSD ()
{
return USD;
}
public void setUSD (USD USD)
{
this.USD = USD;
}
#Override
public String toString()
{
return "ClassPojo [JPY = "+JPY+", USD = "+USD+"]";
}
}
public class JPY
{
#SerializedName("15m")
private double fifitenM;
private String symbol;
private double last;
private double sell;
private double buy;
public double getFifitenM ()
{
return fifitenM;
}
public void setFifitenM (double fifitenM)
{
this.fifitenM = fifitenM;
}
public String getSymbol ()
{
return symbol;
}
public void setSymbol (String symbol)
{
this.symbol = symbol;
}
public double getLast ()
{
return last;
}
public void setLast (double last)
{
this.last = last;
}
public double getSell ()
{
return sell;
}
public void setSell (double sell)
{
this.sell = sell;
}
public double getBuy ()
{
return buy;
}
public void setBuy (double buy)
{
this.buy = buy;
}
#Override
public String toString()
{
return "ClassPojo [15m = "+fifitenM+", symbol = "+symbol+", last = "+last+", sell = "+sell+", buy = "+buy+"]";
}
}
public class USD
{
#SerializedName("15m")
private double fifitenM;
private String symbol;
private double last;
private double sell;
private double buy;
public double getFifitenM ()
{
return fifitenM;
}
public void setFifitenM (double fifitenM)
{
this.fifitenM = fifitenM;
}
public String getSymbol ()
{
return symbol;
}
public void setSymbol (String symbol)
{
this.symbol = symbol;
}
public double getLast ()
{
return last;
}
public void setLast (double last)
{
this.last = last;
}
public double getSell ()
{
return sell;
}
public void setSell (double sell)
{
this.sell = sell;
}
public double getBuy ()
{
return buy;
}
public void setBuy (double buy)
{
this.buy = buy;
}
#Override
public String toString()
{
return "ClassPojo [15m = "+fifitenM+", symbol = "+symbol+", last = "+last+", sell = "+sell+", buy = "+buy+"]";
}
}
public class MainMethd
{
public static void main(String[] args) throws JsonIOException, JsonSyntaxException, FileNotFoundException {
// TODO Auto-generated method stub
JsonParser parser = new JsonParser();
Object obj = parser.parse(new FileReader("C:\\Users\\Documents\\file.json"));
String res = obj.toString();
Gson gson = new Gson();
Container container = new Container();
container = gson.fromJson(res, Container.class);
System.out.println(container.getUSD());
System.out.println("Sell Price : " + container.getUSD().getSymbol()+""+ container.getUSD().getSell());
System.out.println("Buy Price : " + container.getUSD().getSymbol()+""+ container.getUSD().getBuy());
}
}
Output from the main method is:
ClassPojo [15m = 478.68, symbol = $, last = 478.68, sell = 478.68, buy = 478.55]
Sell Price : $478.68
Buy Price : $478.55
Hope this helps.

How to convert the following json string to java object?

I want to convert the following JSON string to a java object:
String jsonString = "{
"libraryname": "My Library",
"mymusic": [
{
"Artist Name": "Aaron",
"Song Name": "Beautiful"
},
{
"Artist Name": "Britney",
"Song Name": "Oops I did It Again"
},
{
"Artist Name": "Britney",
"Song Name": "Stronger"
}
]
}"
My goal is to access it easily something like:
(e.g. MyJsonObject myobj = new MyJsonObject(jsonString)
myobj.mymusic[0].id would give me the ID, myobj.libraryname gives me "My Library").
I've heard of Jackson, but I am unsure how to use it to fit the json string I have since its not just key value pairs due to the "mymusic" list involved. How can I accomplish this with Jackson or is there some easier way I can accomplish this if Jackson is not the best for this?
No need to go with GSON for this; Jackson can do either plain Maps/Lists:
ObjectMapper mapper = new ObjectMapper();
Map<String,Object> map = mapper.readValue(json, Map.class);
or more convenient JSON Tree:
JsonNode rootNode = mapper.readTree(json);
By the way, there is no reason why you could not actually create Java classes and do it (IMO) more conveniently:
public class Library {
#JsonProperty("libraryname")
public String name;
#JsonProperty("mymusic")
public List<Song> songs;
}
public class Song {
#JsonProperty("Artist Name") public String artistName;
#JsonProperty("Song Name") public String songName;
}
Library lib = mapper.readValue(jsonString, Library.class);
Check out Google's Gson: http://code.google.com/p/google-gson/
From their website:
Gson gson = new Gson(); // Or use new GsonBuilder().create();
MyType target2 = gson.fromJson(json, MyType.class); // deserializes json into target2
You would just need to make a MyType class (renamed, of course) with all the fields in the json string. It might get a little more complicated when you're doing the arrays, if you prefer to do all of the parsing manually (also pretty easy) check out http://www.json.org/ and download the Java source for the Json parser objects.
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonObject object = (JsonObject) parser.parse(response);// response will be the json String
YourPojo emp = gson.fromJson(object, YourPojo.class);
Gson is also good for it: http://code.google.com/p/google-gson/
"
Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.
"
Check the API examples: https://sites.google.com/site/gson/gson-user-guide#TOC-Overview
More examples: http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/
In my case, I passed the JSON string as a list. So use the below solution when you pass the list.
ObjectMapper mapper = new ObjectMapper();
String json = "[{\"classifier\":\"M\",\"results\":[{\"opened\":false}]}]";
List<Map<String, Object>> map = mapper
.readValue(json, new TypeReference<List<Map<String, Object>>>(){});
Underscore-java (which I am the developer of) can convert json to Object.
import com.github.underscore.U;
String jsonString = "{\n" +
" \"libraryname\":\"My Library\",\n" +
" \"mymusic\":[{\"Artist Name\":\"Aaron\",\"Song Name\":\"Beautiful\"},\n" +
" {\"Artist Name\":\"Britney\",\"Song Name\":\"Oops I did It Again\"},\n" +
" {\"Artist Name\":\"Britney\",\"Song Name\":\"Stronger\"}]}";
Map<String, Object> jsonObject = U.fromJsonMap(jsonString);
System.out.println(jsonObject);
// {libraryname=My Library, mymusic=[{Artist Name=Aaron, Song Name=Beautiful}, {Artist Name=Britney, Song Name=Oops I did It Again}, {Artist Name=Britney, Song Name=Stronger}]}
System.out.println(U.<String>get(jsonObject, "mymusic[0].Artist Name"));
// Aaron
public void parseEmployeeObject() throws NoSuchFieldException, SecurityException, JsonParseException, JsonMappingException, IOException
{
Gson gson = new Gson();
ObjectMapper mapper = new ObjectMapper();
// convert JSON string to Book object
Object obj = mapper.readValue(Paths.get("src/main/resources/file.json").toFile(), Object.class);
endpoint = this.endpointUrl;
String jsonInString = new Gson().toJson(obj);
JsonRootPojo organisation = gson.fromJson(jsonInString, JsonRootPojo.class);
for(JsonFilter jfil : organisation.getSchedule().getTradeQuery().getFilter())
{
String name = jfil.getName();
String value = jfil.getValue();
}
System.out.println(organisation);
}
{
"schedule": {
"cron": "30 19 2 MON-FRI",
"timezone": "Europe/London",
"tradeQuery": {
"filter": [
{
"name": "bookType",
"operand": "equals",
"value": "FO"
},
{
"name": "bookType",
"operand": "equals",
"value": "FO"
}
],
"parameter": [
{
"name": "format",
"value": "CSV"
},
{
"name": "pagesize",
"value": "1000"
}
]
},
"xslt" :""
}
}
public class JesonSchedulePojo {
public String cron;
public String timezone;
public JsonTradeQuery tradeQuery;
public String xslt;
public String getCron() {
return cron;
}
public void setCron(String cron) {
this.cron = cron;
}
public String getTimezone() {
return timezone;
}
public void setTimezone(String timezone) {
this.timezone = timezone;
}
public JsonTradeQuery getTradeQuery() {
return tradeQuery;
}
public void setTradeQuery(JsonTradeQuery tradeQuery) {
this.tradeQuery = tradeQuery;
}
public String getXslt() {
return xslt;
}
public void setXslt(String xslt) {
this.xslt = xslt;
}
#Override
public String toString() {
return "JesonSchedulePojo [cron=" + cron + ", timezone=" + timezone + ", tradeQuery=" + tradeQuery
+ ", xslt=" + xslt + "]";
}
public class JsonTradeQuery {
public ArrayList<JsonFilter> filter;
public ArrayList<JsonParameter> parameter;
public ArrayList<JsonFilter> getFilter() {
return filter;
}
public void setFilter(ArrayList<JsonFilter> filter) {
this.filter = filter;
}
public ArrayList<JsonParameter> getParameter() {
return parameter;
}
public void setParameter(ArrayList<JsonParameter> parameter) {
this.parameter = parameter;
}
#Override
public String toString() {
return "JsonTradeQuery [filter=" + filter + ", parameter=" + parameter + "]";
}
public class JsonFilter {
public String name;
public String operand;
public String value;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOperand() {
return operand;
}
public void setOperand(String operand) {
this.operand = operand;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
#Override
public String toString() {
return "JsonFilter [name=" + name + ", operand=" + operand + ", value=" + value + "]";
}
public class JsonParameter {
public String name;
public String value;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
#Override
public String toString() {
return "JsonParameter [name=" + name + ", value=" + value + "]";
}
public class JsonRootPojo {
public JesonSchedulePojo schedule;
public JesonSchedulePojo getSchedule() {
return schedule;
}
public void setSchedule(JesonSchedulePojo schedule) {
this.schedule = schedule;
}
#Override
public String toString() {
return "JsonRootPojo [schedule=" + schedule + "]";
}

Categories

Resources