Parsing a JSON document - java

actually I'm struggeling with parsing the following JSON doc: LINK
I have a class which is saving the content in a String (rawData). After that I want to parse it with Gson.
DownloadedCategories dcats = new Gson().fromJson(rawData, DownloadedCategories.class);
My goal is to have a List of an extra datatype of the 21 main categories, and in the extra datatype saved in another List the subcategories.
My approach was to create the new datatype mainCategory which includes the List of the subcategories.
The problem is that i can't do the DownloadedCategories class like this:
public class DownloadedCategories
{
private List<mainCategories> categories;
public List<mainCategories> getCategories;
{
return categories;
}
}
Has someone an idea how to fix my issue?

Looks like that Json from your link is not formatted to fit in your object.
You need to know in which attribute you will put your categories since you are trying to parse a Json array in an object. In your DownloadedCategories the attribute is categories. So you need to wrap your Json in an attribute categories.
String wellFolrmedJson = "{\"categories\": " + rawData + "}";
DownloadedCategories dcats = new Gson().fromJson(wellFolrmedJson , DownloadedCategories.class);
Gson will bind the json array in your Object list.
The best way to parse your data is by using array as starting point like in this example.
mainCategories[] dcats = new Gson().fromJson(rawData , mainCategories[].class);

Related

How can i add additional field to each object in array node using jackson java?

i have list of masters that have two fields that are name and rating and after serialization to array node i need to add one more field to each object
for example i have json
[{"masterName":"Bruce","rating":30},{"masterName":"Tom","rating":25}]
and i have list of servisec in json format that look like that
[{"masterName":"Bruce","services":["hair coloring","massage"]},{"masterName":"Tom","services":["hair coloring","haircut"]}]
i need it to looks something like that
[{"masterName":"Bruce","rating":30,"services":"hair coloring,massage"},{"masterName":"Tom","rating":25,"services":"hair coloring, haircut"}]
How can do it by using jackson?
I would approach it this way. Since you want to use Jackson.
First of all, I would extend the Master class by adding the services (which seems to be an array with Strings).
So the class would look something like this:
public class Master
{
private String masterName;
private int rating;
private List<String> services = new ArrayList<>(); // THE NEW PART
// Whatever you have else in your class
}
Then you could get your JSON array, I am supposing that it comes as a String for simplicity. Serialize this array in an array with Master objects and then you can add the services as said above.
e.g.
String yourJsonString = "[{\"masterName\":\"Bruce\",\"rating\":30},{\"masterName\":\"Tom\",\"rating\":25}]";
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
List<Master> theListOfMasters = new ArrayList<>();
// Read them and put them in an Array
Master[] mastersPlainArr = mapper.readValue(yourJsonString, Master[].class);
theListOfMasters = new ArrayList(Arrays.asList(mastersPlainArr));
// then you can get your masters and edit them..
theListOfMasters.get(0).getServices.add("A NEW SERVICE...");
// And so on...
// Then you can turn them in a JSON array again:
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(theListOfMasters);

Simple way to map csv-table to json with different property-names than csv-headers with gson?

I have got some csv-files, which I want to transform into a json.
Unfortunately the structure of the csv doesn't match the desired json format. a) because csv is a flat structure and the json should be of nested structure. b) because the column headers don't match the json property names.
Illustrating minimal example CSV:
ColumnNameX,ColumnNameY,ColumnNameZ
valueX,valueY,valueZ
should be transformed into this JSON:
{
"XZObject": {
"absurdlyNotNamedLikeCsvHeading": "valueX",
"AlsoNOTColumnNameZ": "valueZ" },
"YyyyyWhy": {
"ThisResemblesColumnNameY": "valueY"
}
I would naively go and make some representing POJO-classes and put in the values by position – like so (pseudocode):
class Container {Fields:XZObject,YyyyyWhy}
class XZObject {Fields:absurdlyNotNamedLikeCsvHeading,AlsoNOTColumnNameZ}
class YyyyyWhy {Fields:ThisResemblesColumnNameY}
new XZObject(absurdlyNotNamedLikeCsvHeading=csvLineElements[0],AlsoNOTColumnNameZ=csvLineElements[2])
new YyyyyWhy(ThisResemblesColumnNameY=csvLineElement[1])
new Container(XZObject,YyyyyWhy)
…then I'd transform the Container object to JSON with gson.
The problem is, when a field in the CSV gets added to the scheme, I'd have to adjust every positional mapping after the new column.
So I wonder: Is there a simple way to map CSV-columns by header to a specific JSON property? Preferably with gson-lib.
In other words: Can I i.e. map the value in column with header "ColumnNameZ" to property "XZobject.AlsoNOTColumnNameZ" in a simple way?
I think parsing the CSV file into Objects is the good way to go.
You can read the first column first, split it and calculate the index of each column at runtime. Then it doesn't matter if you add/remove or shuffle columns
Assuming you read the first line and you have
String firstRow = "ColumnNameX,ColumnNameY,ColumnNameZ";
Parse it this way:
List<String> columnList = Arrays.asList(firstRow.split(","));
int COLUMN_NAME_X_INDEX = columnList.indexOf("ColumnNameX");
int COLUMN_NAME_Y_INDEX = columnList.indexOf("ColumnNameY");
int COLUMN_NAME_Z_INDEX = columnList.indexOf("ColumnNameZ");
Than use your newly found indexes:
XZObject xzObject = new XZObject(csvLineElements[COLUMN_NAME_X_INDEX], csvLineElements[COLUMN_NAME_Z_INDEX]);
YyyyyWhy yyyyyWhy = new YyyyyWhy(csvLineElements[COLUMN_NAME_Y_INDEX]);
Container container = new Container(XZObject,YyyyyWhy);

Get all objects on ArrayList

can some one explain me how to get all categories value from
"categories":[{"1":1,"2":"orange","3":"mango","4":"guava","5":5,"6":6}]
result my like this 1 = 1, and 2 = orange,
what must i do i am stuck in here
public RealmList<CategoryRealm> categories;
or
p.categories = new RealmList<>();
can some one explain to me what must i do in the next method i am stuck tried searching but so damn hard to learn its diferent.
Use GSON library.
Create an object that matches your structure. I'm assuming you have a structure of
{
"categories"://the rest of the stuff here
}
class MyParentObject{
#SerializeName("categories")
ArrayList<String> myList;
}
Then use GSON to create it
MyParentObject obj = (MyParentObject)getGson().fromJson(json, classType);
and your done.
If the base is just the categories string then your json is badly formatted and you may have to do a subString call to get starting index of "[" and go from there into json management.

Logical solution for creating a JSON structure

I am not sure if it possible or not but I think it can be done using JSONArray.put method.
Heres my problem:
I have got two lists:
ArrayList<Students> nativeStudents;
ArrayList<transferStudents> transferStudents = nativeStudents.getTransferStudentsList();
The JSON that I generate with transferStudents list is right here: http://jsfiddle.net/QLh77/2/ using the following code:
public static JSONObject getMyJSONObject( List<?> list )
{
JSONObject json = new JSONObject();
JsonConfig config = new JsonConfig();
config.addIgnoreFieldAnnotation( MyAppJsonIgnore.class );
if( list.size() > 0 )
{
JSONArray array = JSONArray.fromObject( list, config );
json.put( "students", array );
}
else
{
//Empty Array
JSONArray array = new JSONArray();
json.put( "students",
array );
}
return json;
}
Now what I want to get is JSON data with following structure: http://jsfiddle.net/bsa3k/1/ (Notice the tempRollNumber field in both array elements).
I was thinking of doing: (The if condition here is used for a business logic)
if(transferStudents.getNewStudentDetails().getRollNumber() == nativeStudents.getNativeStudentDetails.getStudentId()){
json.put("tempRollNumber", transferStudents.getNewStudentDetails().getRollNumber());
}
but this would add tempRollNumber outsite the array elements, I want this JSON element to be part of every entry of students array.
PS: I cant edit the transferStudents class in order to add tempRollNumber field.
Since no one has come up with anything better I'll turn my comments above into an answer.
The best way to handle this is to create an object model of your data and not create the JSON output yourself. Your app server or container can handle that for you.
Though you cannot change the objects you receive in the List you can extend the object's class to add your own fields. Those fields would then appear in the JSON when you marshall it.

JSON parsing to Java - Android application

I need help with parsing json string in Java Android Appl.
Text of JSON file:
{"data":{"columns":["location_id","name","description","latitude","longitude","error","type","type_id","icon_media_id","item_qty","hidden","force_view"],"rows":[[2,"Editor","",43.076014654537,-89.399642451567,25,"Npc",1,0,1,"0","0"],[3,"Dow Recruiter","",43.07550842555,-89.399381822662,25,"Npc",2,0,1,"0","0"] [4,"Protestor","",43.074933,-89.400438,25,"Npc",3,0,1,"0","0"],[5,"State Legislator","",43.074868061524,-89.402136196317,25,"Npc",4,0,1,"0","0"],[6,"Marchers Bascom","",43.075296413877,-89.403374183615,25,"Node",22,0,1,"0","0"] [7,"Mary","",43.074997865584,-89.404967573966,25,"Npc",7,0,1,"0","0"]]},"returnCode":0,"returnCodeDescription":null}
How can get values: location_id, name, latitude, longitude.
Thanks, Michal.
Using manual parsing you can implement it like this:
JSONArray pages = new JSONArray(jsonString);
for (int i = 0; i < pages.length(); ++i) {
JSONObject rec = pages.getJSONObject(i);
JSONObject jsonPage =rec.getJSONObject("page");
String address = jsonPage.getString("url");
String name = jsonPage.getString("name");
String status = jsonPage.getString("status");
}
in your case note that your outer elemnt data is type of JSONObject and then you have a JSONArray
mine json file:
[{"page":{"created_at":"2011-07-04T12:01:00Z","id":1,"name":"Unknown Page","ping_at":"2011-07-04T12:06:00Z","status":"up","updated_at":"2011-07-04T12:01:00Z","url":"http://www.iana.org/domains/example/","user_id":2}},{"page":{"created_at":"2011-07-04T12:01:03Z","id":3,"name":"Down Page","ping_at":"2011-07-04T12:06:03Z","status":"up","updated_at":"2011-07-04T12:01:03Z","url":"http://www.iana.org/domains/example/","user_id":2}}]
note that mine starts from [, which means an array, but yours from { and then you have [ array inside. If you run it with a debugger, you can see exactly what´s inside your json objects.
There are also better approaches like:
Jackson
Jackson-JR (light-weight Jackson)
GSON
All of them 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.
First of all, you need to know about Json parsing in android, so for that first read this: JSONObject, in that class, you will see the below methods:
getJSONArray(String name)
getJSONObject(String name)
getString(String name)
and many more methods to be used while implementing JSON parsing in android.
Update:
And if you are still confused then click on below link to have many examples available on web: Android JSON Parsing
You need to use the GSON lib
http://code.google.com/p/google-gson/
Object Examples
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
(Serialization)
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);
==> json is {"value1":1,"value2":"abc"}
Note that you can not serialize objects with circular references since that will result in infinite recursion.
(Deserialization)
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
==> obj2 is just like obj
If you mean to navigate easily the Json Tree, you can use JSON Path, that is query system, similar to XPath to XML, that you can use to pick some elements in a json tree using text expressions.
http://code.google.com/p/json-path/ That's a good implementation
If you just mean that you want to parse that JSon you can use Gson from google (that is compatible with Android I guess).
This contains a complete example for your case.

Categories