I have a JSON file like this:
[
{
"number": "3",
"title": "hello_world",
}, {
"number": "2",
"title": "hello_world",
}
]
Before when files had a root element I would use:
Wrapper w = gson.fromJson(JSONSTRING, Wrapper.class);
code but I can't think how to code the Wrapper class as the root element is an array.
I have tried using:
Wrapper[] wrapper = gson.fromJson(jsonLine, Wrapper[].class);
with:
public class Wrapper{
String number;
String title;
}
But haven't had any luck. How else can I read this using this method?
P.S I have got this to work using:
JsonArray entries = (JsonArray) new JsonParser().parse(jsonLine);
String title = ((JsonObject)entries.get(0)).get("title");
But I would prefer to know how to do it (if possible) with both methods.
Problem is caused by comma at the end of (in your case each) JSON object placed in the array:
{
"number": "...",
"title": ".." , //<- see that comma?
}
If you remove them your data will become
[
{
"number": "3",
"title": "hello_world"
}, {
"number": "2",
"title": "hello_world"
}
]
and
Wrapper[] data = gson.fromJson(jElement, Wrapper[].class);
should work fine.
Gson gson = new Gson();
Wrapper[] arr = gson.fromJson(str, Wrapper[].class);
class Wrapper{
int number;
String title;
}
Seems to work fine. But there is an extra , Comma in your string.
[
{
"number" : "3",
"title" : "hello_world"
},
{
"number" : "2",
"title" : "hello_world"
}
]
public static <T> List<T> toList(String json, Class<T> clazz) {
if (null == json) {
return null;
}
Gson gson = new Gson();
return gson.fromJson(json, new TypeToken<T>(){}.getType());
}
sample call:
List<Specifications> objects = GsonUtils.toList(products, Specifications.class);
Wrapper[] data = gson.fromJson(jElement, Wrapper[].class);
Related
**My result of JSONObject to convert as follows bellow code and have searched for many this how to convert using java but I converted that **
{
"result": {
"accountnames": [{
"accountName": "Hari",
"accountId": 878488
}, {
"accountName": "ravi",
"accountId": 878487
}],
"sales": [{
"accountSales": "89",
"accountId": 878488
}, {
"accountName": "98",
"accountId": 878487
}],
"countResult": [{
"accountResult": "945",
"accountId": 878488
}, {
"accountResult": "9452",
"accountId": 878489
}]
}
}
*and this is where the sample code to be converted *
{
"result": [{
"accountName": "Hari",
"accountSales": "89",
"accountResult": "945",
"accountId": 878488
},
{
"accountName": "ravi",
"accountSales": "98",
"accountId": 878487
},
{
"accountResult": "9452",
"accountId": 878489
}
]
}
My required JSON data has to be formatted as below
You need to group all the elements by accountId. You can use something like this depending on the json library that you are using.
Initialize the json object:
JSONObject rootJson = new JSONObject(json);
JSONObject resultJson = rootJson.getJSONObject("result");
Create a map to hold the objects by accountId:
Map<String, JSONObject> accountIds = new HashMap<>();
Then iterate for each key in the json, then for each element in the arrays and then for each property of the object inside the json:
Iterator mainKeys = resultJson.keys();
while (mainKeys.hasNext()) {
String key = (String) mainKeys.next();
JSONArray array = resultJson.getJSONArray(key);
for (int index = 0; index < array.length(); index++) {
JSONObject object = array.getJSONObject(index);
if (object.has("accountId")) {
String accountId = object.get("accountId").toString();
JSONObject accum = accountIds
.computeIfAbsent(accountId, (k) -> new JSONObject());
// depending on the json impl you can use putAll or similar
Iterator objKeys = object.keys();
while (objKeys.hasNext()) {
String property = (String) objKeys.next();
accum.put(property, object.get(property));
}
} else {
// does not have account id, ignore or throw
}
}
}
Finally create the json file and add the elements to the JSONArray:
JSONObject finalJson = new JSONObject();
finalJson.put("result", new JSONArray(accountIds.values()));
System.out.println(finalJson.toString());
(note: the json has an error in sales array accountName instead of accountSales)
Ok, I know that many of questions like that have been asked, but I have a specific question, which none of the others has. I want to know how I'd go on to parse following JSON file with GSON.
{
"BUYER": {
"IGN": "MGlolenstine",
"ProductID": "51"
},
"BUYER": {
"IGN": "MGlolenstine",
"ProductID": "55"
},
"BUYER": {
"IGN": "MGlolenstine",
"ProductID": "0"
},
"BUYER": {
"IGN": "MGlolenstine",
"ProductID": "51"
},
"BUYER": {
"IGN": "MGlolenstine",
"ProductID": "56"
}
}
because when I use this code
Scanner scanner = new Scanner( new File(path) );
String text = scanner.useDelimiter("\\A").next();
Gson gson = new GsonBuilder().create();
ArrayList<Purchases> p = gson.fromJson(new FileReader(path), Purchases.class);
for(int i = 0; i < p.size(); i++){
arg0.sendMessage(ChatColor.GOLD+"Player: "+p.get(i).BUYER.IGN);
arg0.sendMessage(ChatColor.GOLD+"ProductID: "+String.valueOf(p.get(i).BUYER.ProductID));
}
scanner.close();
I get the error
Caused by: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 2 column 12
Here just posting the classes I have for the JSON code
public class Purchases{
PlayerRank BUYER;
}
public class PlayerRank{
String IGN;
int ProductID;
}
The problem is probably me not knowing how the JSON arrays and objects look like.
Could someone please explain the difference between JSONArray and JSONObject in my JSON code?
Thank you in advance.
EDIT: So this is the fixed JSON
{
"buyers" : [
{ "IGN" : "MGlolenstine", "ProductID" : "51" },
{ "IGN" : "MGlolenstine", "ProductID" : "55" },
{ "IGN" : "MGlolenstine", "ProductID" : "0" },
{ "IGN" : "MGlolenstine", "ProductID" : "51" },
{ "IGN" : "MGlolenstine", "ProductID" : "56" }
]
}
Fixed Java code:
Scanner scanner = new Scanner( new File(path) );
String text = scanner.useDelimiter("\\A").next();
Gson gson = new GsonBuilder().create();
Purchases p = gson.fromJson(new FileReader(path), Purchases.class);
for(int i = 0; i < p.buyers.length; i++){
arg0.sendMessage(ChatColor.GOLD+"Player: "+p.buyers[i].IGN);
arg0.sendMessage(ChatColor.GOLD+"ProductID: "+String.valueOf(p.buyers[i].ProductID));
}
And lastly the classes:
public class Purchases{
PlayerRank buyers[];
}
public class PlayerRank{
String IGN;
int ProductID;
}
Thanks to everyone for the help!
JSON Objects are enclosed directly in curly brackets {} vs. JSON Arrays that are enclosed in square brackets [] inside JSON Objects.
The classes Purchases and PlayerRank should be defined in this way:
public class Purchases{
#SerializedName("buyers") protected ArrayList<PlayerRank> buyers;
...
}
public class PlayerRank{
#SerializedName("IGN") protected String ign;
#SerializedName("ProductID") protected int productId;
...
}
Note the SerializedName notation that lets you decouple the name of the objects/arrays in the json file from the names of your java properties.
The protected I added to the properties just makes it explicit what the original classes defaulted to in the original code.
The JSON file should be something like this:
{
"buyers" : [
{ "IGN": "MGlolenstine", "ProductID": "51"},
{ "IGN": "MGlolenstine", "ProductID": "55"},
...
{ "IGN": "MGlolenstine", "ProductID": "56"}
]
}
And to read the JSON into a variable:
Purchases p = gson.fromJson(new FileReader(path), Purchases.class);
How to convert following type Json array in "tags_name": ["Activity Based"] in android and store data using getter setter methods.How to create POJO class, and how to handle when array is empty.I am struck with this concept.I tried this following way. Please guide me to resolve this issue.
API
"postlist": [
{
"posts": {
"pm_post_id": "4647",
},
"tags_name": [
"Activity Based"
],
"images_count": 0,
"images": [],
"post_user": [
{
"first_name": "Michelle",
"last_name": "Smith",
"profile_pic": "profess_sw_engg.jpg"
}
],
"is_encourage_user": true,
"encourage_feed_id": "992"
},
{
"posts": {
"pm_post_id": "4647",
},
"tags_name": [],
"images_count": 2,
"images": [
{
"gallery_id": "5549",
"name": "IMG_20161012_1832491.jpg",
},
{
"gallery_id": "5550",
"name": "IMG_20161012_1832441.jpg",
}
],
"post_user": [
{
"first_name": "Michelle",
"last_name": "Smith",
"profile_pic": "profess_sw_engg.jpg"
}
],
"is_encourage_user": true,
"encourage_feed_id": "993"
}
]
In Java i've use Following code.
try {
JSONArray tagNameArr = tempPostObject.getJSONArray("tags_name");
for(int iloop=0;i<tagNameArr.length();iloop++)
{
String street = tagNameArr.getString(iloop);
Log.i("..........",""+street);
}
} catch (Exception e) {
e.printStackTrace();
}
try this to get value of tags_name JSONArray.
ArrayList<String> temp = new ArrayList<String>();
JSONArray tagName= jsonResponse.getJSONArray("tags_name");
for(int j=0;j<tagName.length();j++){
temp.add(tagName.getString(j));
}
Use jsonschema2pojo.org service and Gson converter (lib from Google). select Gson converter on the site.
You can use gson
Gson gson = new GsonBuilder().serializeNulls().create();
RestaurantLoginResponseClass restaurantLoginResponse = gson.fromJson(loginResponseJsonString, RestaurantLoginResponseClass.class);
Add dependencies in app.gradle
compile 'com.google.code.gson:gson:2.6.2'
#MohanRaj , why you would to parse it ! , it is not clear , if you would to get the values and retain it in java object or save it in file system , you can use :
Gs
Gson gson = new Gson();
Staff obj = gson.fromJson(jsonInString, Staff.class);
if you have a list of object inside your json
you can create a list in your staff class something like :
#SerializedName("hits")
private List<Car> cars = new ArrayList<Car>();
GSON can understood it and parse the incoming list to those object .
you can get POJO from familiar JSON to java POJO tools :
http://www.jsonschema2pojo.org/
and you can check for more info https://sites.google.com/site/gson/gson-user-guide
http://www.java2blog.com/2013/11/gson-example-read-and-write-json.html
where I want to check which elements of the 1st file are missing in the second one.
Here is the form of the first one:
[
{
"pId": "pId1",
"Platform":["ios","and","web","winph","win"],
"Name": "ay",
"ShortDescription": "Mobi",
"Detail" : {
"IncentiveInformation": "ppp",
"DisplayName" : "vvv!",
"Description" : "mmm",
"TermsAndConditions": ".."
}
},
{
"pId": "pId2",
"Platform":["afasd","sdfsd","pppp","asdas","win"],
"Name": "ay",
"ShortDescription": "mob",
"PromotionDetail": {
"DebugMode": false,
"PromoDate": ["2015.01.01-00:01","2015.01.01-23:59"],
"IncentiveInformation": "PRO",
"Name": "iTunes",
"ShortDescription": "Punkte sammeln bei iTunes",
"DisplayName": null,
"Description": null,
"ImageURL": null,
"JumpToShopURL": "urlHere",
"JumpToShopName" : "Zu iTunes"
}
},
{
"pId": "pId3",
"Platform":["wqdsa"],
"Name": "poti",
"ShortDescription": "pun",
"ImageURL": "url.here",
"Promotion" : false,
"PromotionDetail": {
"DebugMode": false,
"PromoDate": ["2015.01.01-00:00","2015.01.01-23:59"],
"IncentiveInformation": "ppeur",
"Name": "namehere",
"ShortDescription": "tune",
"DisplayName": null,
"Description": null,
"ImageURL": null,
"JumpToShopURL": "noq",
"JumpToShopName" : "Zu"
}
}
]
and here is the form of the 2nd one:
{
"pList": [{
"shortName": "bb",
"longName": "bb",
"pId": "pId2",
"featured": true,
"pLog": "url.here",
"incentivation": "eu",
"details": {
"teaserImage": "image.url",
"description": "desc here",
"jumpToShopURL": "nurl",
"jumpToShopButton": "zubay",
"terms": [{
"headline": "Wichtig",
"body": "bodyline"
}]
}
}, {
"shortName": "one short name",
"longName": "bkp",
"pId": "pId1",
"featured": true,
"pLo": "some.pLo",
"incentivation": "1p",
"details": {
"teaserImage": "some.url",
"description": "desc",
"jumpToShopURL": "short url",
"jumpToShopButton": "Zuay",
"terms": [{
"headline": "Wichtig",
"body": "bodyhere"
}]
}
}]
}
Si I thought to save all the "pId" of the first one in a List(or array) and then iterate over that list and check for each one if the pId exists in the new one.
So I tried this, but it is not working..
Could anyone help me with that? I tried a bit and then I found that I have too many difficulties, to get the pIds saved in a list or an array.
So has someone an idea?
import java.io.*;
import org.json.*;
public class MainDriver {
public static void main(String[] args) throws JSONException {
String jsonData = readFile("C:\\Users\\kbelkhiria\\Desktop\\Karim_JSON\\alt.json");
JSONObject jobj = new JSONObject(jsonData);
JSONArray jarr = new JSONArray(jobj.getJSONArray("pList").toString());
for(int i = 0; i < jarr.length(); i++)
System.out.println("id: " + jarr.getString(i));
}
public static String readFile(String filename) {
String result = "";
try {
BufferedReader br = new BufferedReader(new FileReader(filename));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
result = sb.toString();
} catch(Exception e) {
e.printStackTrace();
}
return result;
}
}
For the 2nd form, you have an JSONObject, but it contains some errors. Please fix them, or use a the 1st form again.
SOLUTION
I found some errors in the second file so I suggest the following edits:
change "jumpToShopURL": nurl", to "jumpToShopURL": null,
add a comma at the end of "description": "desc"
add a comma at the end of "jumpToShopURL": "short url"
For the code, you can use the following lines:
/*first file*/
String jsonData = readFile("C:\\Users\\kbelkhiria\\Desktop\\Karim_JSON\\alt.json");
JSONArray jarr = new JSONArray(jsonData);
/*array of first file's ids*/
ArrayList<String> srcArray = new ArrayList<>();
for(int i = 0; i < jarr.length(); i++) {
srcArray.add(jarr.getJSONObject(i).getString("pId"));
}
/*second file*/
// second form in a seperate file
JSONObject obj = new JSONObject(readFile("C:\\Users\\kbelkhiria\\Desktop\\Karim_JSON\\alt2.json"));
JSONArray arr = obj.getJSONArray("pList");
/*array of second file's ids*/
ArrayList<String> dstArray = new ArrayList<>();
for(int i = 0; i < arr.length(); i++) {
dstArray.add(jarr.getJSONObject(i).getString("pId"));
}
for (String string : srcArray) {
if (dstArray.indexOf(string)==-1)
System.out.println(string + " is missing in the second file");
}
Luckily for you there are already developed libraries to parse any JSON string, like the one's you provided. One of the most popular is
org.json
Using this you can write code similar to this:
import org.json.*;
String myString = ".." // The String representation you provided
JSONObject obj = new JSONObject(myString);
JSONArray arr = obj.getJSONArray("pList");
Another popular library for the same task is GSON
One possible solution using Jackson is the following:
private static final String JSON1 = // first json;
private static final String JSON2 = //second json;
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
List<LinkedHashMap> list1 = Arrays.asList(mapper.readValue(JSON1, LinkedHashMap[].class));
List<LinkedHashMap> list2 = Arrays.asList(mapper.readValue(mapper.readTree(JSON2).get("pList").toString(), LinkedHashMap[].class));
List<LinkedHashMap> missingItens = new ArrayList<>();
for (LinkedHashMap o1 : list1) {
if (!objectExistsInList(o1.get("pId").toString(), list2)) {
missingItens.add(o1);
}
}
}
private static boolean objectExistsInList(String pIdValue, List<LinkedHashMap> objs) {
for (LinkedHashMap map : objs) {
if (map.containsValue(pIdValue)) {
return true;
}
}
return false;
}
Please keep in mind this is a very specific implementation to the given JSONs.
I am creating an application which it will send http request to a web server. The return will be in json. Here is how the json look like
[//I used a tool to make it beautiful and easy to read.
{
"item_name": "Adame",
"item_type": "Special",
"item": "Chestplate",
"item_min_lvl": "50",
"enchantment": {
"health": "0.3",
"dam": "24%",
"life": "0.1",
"xp": "24%",
"loot": "22%"
},
"def": "73"
},
{
"item_name": "Sticks'",
"item_type": "Unique",
"item": "Stick",
"item_min_lvl": "4",
"enchantment": {
"health": "0.6",
"mana": "1",
"dam": "12%",
"life": "0.3",
"xp": "17%",
"loot": "17%"
},
"min_dam": "39",
"max_dam": "34"
},
{
"item_name": "Sword'",
"item_type": "Unique",
"item": "Sword",
"item_min_lvl": "8",
"enchantment": [], //colonm 30 is [
"min_dam": "9",
"max_dam": "10"
}
]
Are you can see, the data inside the array are different. I got this error, Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 30. This is my code:
MyJSON[] data = gson.from(jsonString, MyJSON[].class);
class MyJSON {
String item_name;
String item_type;
String item;
String item_min_lvl;
Enchantment enchantment;
String min_dam;
String max_dam;
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("\nitem_name:").append(item_name);
builder.append("\nitem_type:").append(item_type);
builder.append("\nitem:").append(item);
builder.append("\nitem_min_lvl:").append(item_min_lvl);
builder.append("\n\nEnchantment Details:");
builder.append("\nhealth:").append(enchantment.health);
builder.append("\ndam:").append(enchantment.dam);
builder.append("\nlife:").append(enchantment.life);
builder.append("\nxp:").append(enchantment.xp);
builder.append("\nloot:").append(enchantment.loot);
return builder.toString();
}
}
class Enchantment {
String health;
String dam;
String life;
String xp;
String loot;
String mana;
}
Can anyone help me to improve my code so my code an parse the json in different case. Thanks in advanced. (P.s. that's not my web server so I can't do anything with the json)
Basically this line of JSON
"enchantment": [], //colonm 30 is [
doesn't match your POJO. You're expecting an Enchantment object, but the JSON is giving you an array. Fix your JSON to return an empty JSON object or nothing at all for the enchantment pair.
"enchantment": {}
This is a Valid JSON unless you have added comments just to show lines where is the issue?
Comments should not be part of JSON.
Here is the code that I have already shared you at you another post Java - Json deserialize data [].
You have to use ArrayList<Map<String, Object>> because the entries in the JSON string are not symmetric. You can't convert it into POJO in this case.
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new FileReader(new File("resources/json2.txt")));
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
reader.close();
Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<Map<String, Object>>>() {
}.getType();
ArrayList<Map<String, Object>> list = gson.fromJson(builder.toString(), listType);
for (Map<String, Object> json : list) {
for (String key : json.keySet()) {
System.out.println(key + ":" + json.get(key));
}
System.out.println("===========");
}
output:
item_name:Adame
item_type:Special
item:Chestplate
item_min_lvl:50
enchantment:{health=0.3, dam=24%, life=0.1, xp=24%, loot=22%}
def:73
===========
item_name:Sticks'
item_type:Unique
item:Stick
item_min_lvl:4
enchantment:{health=0.6, mana=1, dam=12%, life=0.3, xp=17%, loot=17%}
min_dam:39
max_dam:34
===========
item_name:Sword'
item_type:Unique
item:Sword
item_min_lvl:8
enchantment:[]
min_dam:9
max_dam:10
===========
EDIT
enchantment return something like
enchantment:{health=0.6, mana=1, dam=12%, life=0.3, xp=17%, loot=17%}.
How can I get for example health?
Type mapType = new TypeToken<Map<String, String>>() {
}.getType();
String string = "{health=0.6, mana=1, dam=12%, life=0.3, xp=17%, loot=17%}";
Map<String, String> map = new Gson().fromJson(string, mapType);
for (String key : map.keySet()) {
System.out.println(key + ":" + map.get(key));
}
output:
health:0.6
mana:1
dam:12%
life:0.3
xp:17%
loot:17%
You can create a custom list type in Gson's fromJson() method to map it to a list of POJOs
Type listType = new TypeToken<ArrayList<Enhancement>>() {}.getType();
List<Enhancement> enhancements = new Gson().fromJson(jsonString, listType);
You will get a List<Enhancement>.