I am trying to convert JSON string to simple java object but it is returning null. Below are the class details.
JSON String:
{"menu":
{"id": "file",
"value": "File",
}
}
This is parsable class:
public static void main(String[] args) {
try {
Reader r = new
InputStreamReader(TestGson.class.getResourceAsStream("testdata.json"), "UTF-8");
String s = Helper.readAll(r);
Gson gson = new Gson();
Menu m = gson.fromJson(s, Menu.class);
System.out.println(m.getId());
System.out.println(m.getValue());
} catch (IOException e) {
e.printStackTrace();
}
}
Below are th model class:
public class Menu {
String id;
String 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;
}
public String toString() {
return String.format("id: %s, value: %d", id, value);
}
}
Everytime i am getting null. Can anyone please help me?
Your JSON is an object with a field menu.
If you add the same in your Java it works:
class MenuWrapper {
Menu menu;
public Menu getMenu() { return menu; }
public void setMenu(Menu m) { menu = m; }
}
And an example:
public static void main(String[] args) {
String json = "{\"menu\": {\"id\": \"file\", \"value\": \"File\"} }";
Gson gson = new Gson();
MenuWrapper m = gson.fromJson(json, MenuWrapper.class);
System.out.println(m.getMenu().getId());
System.out.println(m.getMenu().getValue());
}
It will print:
file
File
And your JSON: {"menu": {"id": "file", "value": "File", } } has an error, it has an extra comma. It should be:
{"menu": {"id": "file", "value": "File" } }
What I have found helpful with Gson is to create an an instance of the class, call toJson() on it and compare the generated string with the string I am trying to parse.
Related
{
{
"1234": {
"name": "bob"
}
},
{
"5678": {
"name": "dan"
}
}
}
I have a class representing name (and other fields, I've just made it simple for this question). But the each element is key'd with the id of the person.
I've tried several things including:
class Name {
String Name;
//getter and setter
}
class NameId {
String id;
Name name;
//getter and setters
}
//json is the string containing of the above json
ArrayList<NameId> map = objectMapper.readValue(json, ArrayList.class);
for (Object m : map) {
LinkedHashMap<String, NameId> l = (LinkedHashMap)m;
Map<String, NameId> value = (Map<String, NameId>) l;
//System.out.println(l);
//System.out.println(value);
for (Object key : value.keySet()) {
System.out.println("key: " + key);
System.out.println("obj: " + value.get(key));
NameId nameId = (NameId)value.get(key);
}
}
The problem I have is it doesn't allow that cast to NameId. The error I get is:
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to NameId
Any ideas on the best way to parse such a json string like this properly?
Your json is malformed. You need the square brackets around it otherwise it isn't considered a json array. If your json looks like (for example)
[
{
"1234" : {
"name" : "dan"
}
},
{
"5678" : {
"name" : "mike"
}
}
]
you can write a custom deserializer for the object mapper. See the working example below:
public static void main(String... args) throws Exception {
String testJson = "[{ \"1234\" : { \"name\" : \"dan\" } },{ \"5678\" : { \"name\" : \"mike\" } }]";
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(NameId.class, new MyDeserializer());
mapper.registerModule(module);
ArrayList<NameId> map = mapper.readValue(testJson.getBytes(), new TypeReference<List<NameId>>() {
});
for (NameId m : map) {
System.out.println(m.id);
System.out.println(m.name.name);
System.out.println("----");
}
}
#JsonDeserialize(contentUsing = MyDeserializer.class)
static class NameId {
String id;
Name name;
//getter and setters
}
static class Name {
String name;
//getter and setter
}
static class MyDeserializer extends JsonDeserializer<NameId> {
#Override
public NameId deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
JsonNode node = p.getCodec().readTree(p);
Map.Entry<String, JsonNode> nodeData = node.fields().next();
String id = nodeData.getKey();
String name = nodeData.getValue().get("name").asText();
Name nameObj = new Name();
nameObj.name = name;
NameId nameIdObj = new NameId();
nameIdObj.name = nameObj;
nameIdObj.id = id;
return nameIdObj;
}
}
try this
Iterator<String> iterator1 =outerObject.keys();
while(iterator1.hasNext())
{
JsonObject innerObject=outerObject.getJsonObject(iterator1.next());
Iterator<String> iterator2=innerObject.keys();
while(iterator2.hasNext()){
String name=innerObject.getString(iterator2.next());
}
}
Your json is not valid. Maybe a little bit different:
{
"1234": {
"name": "bob"
},
"5678": {
"name": "dan"
}
}
And you could model something like:
class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And instead of attemping to use a list, use a map:
Map<Integer, Person> map = new ObjectMapper().readValue(json,
TypeFactory.defaultInstance()
.constructMapType(Map.class, Integer.class, Person.class));
no custom deserializer needed.
first, the json file as #klaimmore suggested (named test.json):
{
"1234": {
"name": "bob"
},
"5678": {
"name": "dan"
}
}
Secondly. here's the 2 separate class files:
#JsonDeserialize
public class Name {
String name;
public Name(String name) {
this.name = name;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
}
and
#JsonDeserialize
public class NameId {
Name name;
String id;
/**
* #return the id
*/
public String getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(String id) {
this.id = id;
}
/**
* #return the name
*/
public Name getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(Name name) {
this.name = name;
}
}
and the extra simple json parser class.
public class JsonParser {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
String jsonString = new String(Files.readAllBytes(Paths.get("test.json")));
ObjectMapper mapper = new ObjectMapper();
Map<String,NameId> nameIdList = mapper.readValue(jsonString, new TypeReference<Map<String,NameId>>(){});
nameIdList.entrySet().forEach(nameIdEntry -> System.out.println("name id is: " + nameIdEntry.getKey() +
" and name is: " + nameIdEntry.getValue().getName().getName()));
}
}
also. this is pretty much a dupe of How to convert json string to list of java objects. you should read this.
The Gist
I tried to deserialize some JSON text with GSON. The JSON string had values defined. However, the deserialized string has null values.
Exactly what I did
I tried to deserialize some JSON text with GSON
SomeSpec deserializedJson = GSON.fromJson(serializedJson, SomeSpec.class);
where serializedJson is a string containing
{
"some_class": "abc.def.SomeClass",
"stuff": [
"FOO",
"BAR",
],
"definition": {
"values": [
{ "feature": "FOO", "value": 1.0 },
{ "feature": "BAR", "value": 1.0 },
]
}
}
and SomeSpec is a java class containing:
package somepackagepath;
import java.util.List;
public class SomeSpec {
private List<FeatureValueSpec> _values;
private List<String> _postProcessFunctions;
public List<FeatureValueSpec> getValues() {
return _values;
}
public List<String> getPostProcessFunctions() {
return _postProcessFunctions;
}
public static class FeatureValueSpec {
private String _feature;
private float _value;
public String getFeature() {
return _feature;
}
public float getValue() {
return _value;
}
}
}
The deserialized object had only null fields even though the JSON clearly had those fields defined.
First: There are two errors in your JSON in Arrays. There are extra commas at end of each array.
Second your models should look like this
public class Values
{
private String value;
private String feature;
public String getValue ()
{
return value;
}
public void setValue (String value)
{
this.value = value;
}
public String getFeature ()
{
return feature;
}
public void setFeature (String feature)
{
this.feature = feature;
}
}
public class Definition
{
private Values[] values;
public Values[] getValues ()
{
return values;
}
public void setValues (Values[] values)
{
this.values = values;
}
}
public class MyPojo
{
private Definition definition;
private String[] stuff;
private String some_class;
public Definition getDefinition ()
{
return definition;
}
public void setDefinition (Definition definition)
{
this.definition = definition;
}
public String[] getStuff ()
{
return stuff;
}
public void setStuff (String[] stuff)
{
this.stuff = stuff;
}
public String getSome_class ()
{
return some_class;
}
public void setSome_class (String some_class)
{
this.some_class = some_class;
}
}
Sometimes during deserialization the null is getting converted to "null". Is there a way I can avoid this?
{
"item" : {
"title": "null",
"id" : "134df"
}
}
I want it as
{
"item" : {
"title": null,
"id" : "134df"
}
}
or
{
"item" : {
"title": "",
"id": "134df"
}
}
You can achieve it by using Google JSON i.e gson.
If you are setting null against the title, then while converting the Object to JSON at that time title will not be available in the JSON string.
After that you can check a condition whether the object is available or not in the JSON and do the further task.
Here is the code spinet.
import com.google.gson.Gson;
public class JackSonObjectMapperExample {
public static void main(String[] args){
Item item = new Item();
item.setId("134df");
item.setTitle(null);
POJOExample pojo = new POJOExample();
pojo.setItem(item);
Gson gson = new Gson();
String jsonInString = gson.toJson(pojo);
System.out.println("=================>>"+jsonInString);
}
}
class POJOExample{
private Item item;
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
}
class Item{
private String title;
private String id;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
output:
=================>>{"item":{"id":"134df"}}
Hope, this will help you.
I have JSON like this
{
"data":
[
{
"id": 1,
"Name": "Choc Cake",
"Image": "1.jpg",
"Category": "Meal",
"Method": "",
"Ingredients":
[
{
"name": "1 Cup Ice"
},
{
"name": "1 Bag Beans"
}
]
},
{
"id": 2,
"Name": "Ice Cake",
"Image": "dfdsfdsfsdfdfdsf.jpg",
"Category": "Meal",
"Method": "",
"Ingredients":
[
{
"name": "1 Cup Ice"
}
]
}
]
}
I am using JSON Object to de-Serialize the data
this is what i am trying to
JSONObject jsonObj = new JSONObject(jsonStr);
String first = jsonObj.getJSONObject("data").getString("name");
System.out.println(first);
But a Cant seem to get the name or anything
Not sure what i am doing wrong?
and then i am trying to display it into a listview but haven't got to that part yet
data is a JSON Array, not a JSONObject
try: jsonObj.getJSONArray("data").getJSONObject(0).getString("name")
also note the difference between getString and optString, if you don't want an exception on null use the later.
First parse your Json from below method,
private ArrayList<String> getStringFromJson(String jsonStr)
{
ArrayList<String> mNames = new ArrayList<String>();
JSONArray array = new JSONArray(jsonStr);
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
mNames= row.getString("Name");
}
return mNames;
}
try {
JSONObject jsonObj = new JSONObject(jsonStr);
jsonObj.getJSONArray("data").getJSONObject(0).getString("name")
} catch (JSONException e) {
}
Data is a json array. Use getJsonObject for json objects.
Refer to this example to create a ListView and populate it's adapter with data from a json object.
Use GSON instead JSON. Hope it helps you.
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
List<Data> datas= new ArrayList<Data>();
datas= Arrays.asList(gson.fromJson(jsonString, Data[].class));
public class Ingredients {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private String name;
}
public class Data {
private int id;
private String Name;
private String Image;
private String Category;
private String Method;
public List<Ingredients> getIngredients() {
return Ingredients;
}
public void setIngredients(List<Ingredients> ingredients) {
Ingredients = ingredients;
}
private List<Ingredients> Ingredients = new ArrayList<Ingredients>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
public String getCategory() {
return Category;
}
public void setCategory(String category) {
Category = category;
}
public String getMethod() {
return Method;
}
public void setMethod(String method) {
Method = method;
}
}
I want to convert a JSONObject (array) to a list of Objects.
As I am very new with java i am having quite some problems.
JSON:
"products": [
{
"pid": "0",
"name": "Product Na",
"kategorie": "Category",
"beschreibung": "Description",
"bild": "http:\/\/arsdecora.net\/wp-content\/uploads\/2015\/04\/B1696.jpg",
"preis": "0"
},
{
"pid": "1160",
"name": "Beispiel B",
"kategorie": null,
"beschreibung": null,
"bild": "http:\/\/arsdecora.net\/wp-content\/uploads\/2015\/04\/B1696.jpg",
"preis": "0"
},
Product class:
public class Produkt {
public String id;
public String name;
public String categorie;
public String description;
public String image;
public double price;
}
I have tried several things with gson, but ultimately nothing worked.
I don't need a working code, just a hint on how to deserialize the JSON by the tags.
I hope you can help me. Thanks in advance!
Considering that your request or string data is in JSONObject jsonArray. Below code can help you get the response in List using TypeToken.
JSONArray jsonArray = jsonResponse.getJSONArray("products");
String newList = jsonArray.toString();
Gson gson = new Gson();
Type typeOfProduktList = new TypeToken<ArrayList<Produkt>>() {}.getType();
List<Produkt> finalList = gson.fromJson(newList, typeOfProduktList);
Now, you can return the finalList in the end or process it as per your wish.
Try creating a class that has a list of products. Here is a complete example:
Add brackets around your json data like this:
{
"products": [
{
"pid": "0",
"name": "Product Na",
"kategorie": "Category",
"beschreibung": "Description",
"bild": "http:\/\/arsdecora.net\/wp-content\/uploads\/2015\/04\/B1696.jpg",
"preis": "0"
},
{
"pid": "1160",
"name": "Beispiel B",
"kategorie": null,
"beschreibung": null,
"bild": "http:\/\/arsdecora.net\/wp-content\/uploads\/2015\/04\/B1696.jpg",
"preis": "0"
}
]
}
Here are the classes you need:
Data class:
public class Data {
private List<Product> products;
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
}
Product class:
public class Product {
private String pid;
private String name;
private String kategorie;
private String beschreigung;
private String bild;
private String preis;
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getKategorie() {
return kategorie;
}
public void setKategorie(String kategorie) {
this.kategorie = kategorie;
}
public String getBeschreigung() {
return beschreigung;
}
public void setBeschreigung(String beschreigung) {
this.beschreigung = beschreigung;
}
public String getBild() {
return bild;
}
public void setBild(String bild) {
this.bild = bild;
}
public String getPreis() {
return preis;
}
public void setPreis(String preis) {
this.preis = preis;
}
}
GsonTest class:
public class GsonTest {
public static void main(String[] args) {
Gson gson = new Gson();
Object obj;
try {
JsonParser parser = new JsonParser();
obj = parser.parse(new FileReader("C:\data.json"));
JsonObject jsonObject = (JsonObject) obj;
Data data = gson.fromJson(jsonObject, Data.class);
} catch (JsonIOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonSyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}