How to Create Json with array list Android? - android

i need to create JSON and set array list on a field.
We have api of C#,.NET and they want me to send a JSON.
They want these parameters to be used:
"CustomerID": 1,
"AddressID": 1,
"Array": arraylist
how can i do that ?

You can use Google's Json library called Gson for serialization and deserialization.
I am assuming you are using Android Studio, if not you can still import this library to your project.
First, add this line to your module's build.gradle file's dependencies:
compile 'com.google.code.gson:gson:2.3.1'
Then create a class, add your variables and tag them for JSON:
public class ToJson {
#SerializedName("CustomerID")
public int CustomerId;
#SerializedName("AddressID")
public int AddressId;
#SerializedName("Array")
public List array;
}
Create an object and populate:
ToJson toJson = new ToJson();
toJson.CustomerId = 1;
toJson.AddressId = 1;
toJson.array = new ArrayList<>();
toJson.array.add("Item 1");
toJson.array.add("Item 2");
toJson.array.add("Item 3");
Then create a Gson object and use it for serialization:
Gson gson = new Gson();
String JSON = gson.toJson(toJson);
The output JSON string is:
{
"Array": [
"Item 1",
"Item 2",
"Item 3"
],
"CustomerID": 1,
"AddressID": 1
}
This is simple as that.
You can also check Gson User Guide for further information about serialization/deserialization.

I can recommend using Jackson.
You only need to implement a POJO and annotate it.
Check this out. http://www.studytrails.com/java/json/java-jackson-Serialization-list.jsp

Related

How to read the object inside a JSON array

I have JSON in this format.
I m trying to create serialization class to store the value.
How to read the "personaldata" field?
I am making a separate class PersonalData to read it.
And in my main serialization class I am reading it as
List<PersonalData>personalData
Is it the right way to do it?
If so, how will I fetch the personal data values?
{
"result": [
{
"name": 0,
"age": 1,
"class": 0,
// More data here
"personalData": {
"isMarried": true,
"isEligible": false,
"Indian": true
}
}
]
}
If you are using some parser like GSON or LoganSquare you can use their annotations and it will be really easy to parse JSON directly to your model. Otherwise if you are using native JSON API
You can use something like this
JSONArray arr=new JSONArray(response);
JSONObject personalData=arr.getJSONObject("personalData");
I am making a separate class PersonalData to read it..
Okay, then that is how you access it. By getting that object from some parent Results object.
For example, given some implementation of the below classes, once you deserialize the JSON, you use Results.getResults().get(0).getPersonalData();
public class Results {
ArrayList<ResultData> result;
// TODO: write getResults()
}
public class ResultData {
int name, age, class;
// Some more data
PersonalData personalData;
// TODO: write getPersonalData()
}
public class PersonalData {
boolean isMarried, isEligible, Indian;
}

How to structure a Map from Json that has duplicate keys

Ok so I have this piece of JSON that I want to parse with Gson. I would like the Strings to be the values and the longs to be the keys.
{"completed_questions":[["String",12345],...]}
The issue is the data type, when I try a Map<String, Long> it parses everything but gives me an error because of the duplicate String keys.
I tried to reverse it thinking Gson would know to switch them around but when I tried Map<Long, String> I got an error about not being able to parse my Strings as Longs.
To get it to work I created a swap map class that takes the Key and Value types and swaps them like so public class SwapMap<K, V> implements Map<K, V> however translating the swapped map actions like put/get/remove seem to be pretty difficult to make work.
What's the best way to parse this with Gson even though the strings aren't unique? (But the numbers are)
JSON doesn't allow identical keys on the same level in a json object. It seems like you are trying to map a json array to a java map.
Based on the following data structure, you would need a list if you want to use the default conversion provided by Gson.
{
"completed_questions": [
[
"String",
12345
],
[
"String",
12345
]
]
}
Here is a quick implementation:
private static void mapToObject() {
String json = "{\"completed_questions\":[[\"String\",12345],[\"String\",123456]]}";
Gson gson = new Gson();
CompletedQuestions questions = gson.fromJson(json, CompletedQuestions.class);
for (List<String> arr : questions.getCompleted_questions()) {
for (String val : arr) {
System.out.print(val + " ");
}
System.out.println();
}
}
public static class CompletedQuestions {
List<List<String>> completed_questions;
public List<List<String>> getCompleted_questions() {
return completed_questions;
}
}
This outputs:
String 12345
String 123456
The thing to note is that I am using a list for mapping purposes which closely resembles the data model provided.
This will require you to do the conversion to long yourself. But the way that json string looks. It seems like you would need to operate on the indices. If you have control over the json structure, I would recommending creating a better model. Other wise you can do something like list.get(0) -> your key list.get(1) -> your value which is the long on the inner list.
So what I did is just made a custom Gson Deserializer that mapped these values to a LongSparseArray<String>, which is the best way to go about it.
This is the relevant parts of the Deserializer:
for (JsonElement array : jsonObject.get("my_key").getAsJsonArray()) {
if (array.getAsJsonArray().size() == 2) {
String value = array.getAsJsonArray().get(VALUE).getAsString();
long key = array.getAsJsonArray().get(KEY).getAsLong();
progress.completedActivities.put(key, value);
}
}
Then I just added it to my Gson creator like so:
#Provides #Singleton Gson provideGson() {
return new GsonBuilder()
.registerTypeAdapter(MyClass.class, new MyClass())
.create();
}

how to parse array inside object through gson in android

I want to parse array inside object through GSON.. for Example
{
'title': 'Java Puzzlers: Traps, Pitfalls, and Corner Cases',
'isbn': '032133678X',
'authors':[
{
'id': 1,
'name': 'Joshua Bloch'
},
{
'id': 2,
'name': 'Neal Gafter'
}
]
}
I am only able to parse only object i.e. title, ISBN and got its value but i don't know how to get the value of authors? Please help ,I am using JSON parsing through GSON in android..
ArrayList<Authors> lAuthors = new ArrayList<Authors>();
List<Authors> list = new Gson().fromJson(json, lAuthors.getClass());
for (Object a : list)
{
System.out.println(a);
}
This will give you values in class Author's object.
public class Author{
int id;
String name;
//getter setter here
}
Hope it helps.
those are usefull links for Nasted JSON parsing examples :
Parsing JSON nested array with GSON on Android
http://www.javacreed.com/simple-gson-example/

Gson to convert JSON to Object that contain HastMap of Objects?

I have a problem that I have no idea about this, can anyone help me:
Ex we have a json:
{
"status":"0",
"result": {
"object1": {
"name":"name1",
"age":"21"
},
"object2": {
"event":"new year",
"date":"date"
},
"object1_1": {
"name":"name2",
"age":"22"
},
"object2_1": {
"event":"birthday",
"date":"date"
}
}
}
you can try convert to object by using jackson json.
http://jackson.codehaus.org/
If you want to deserialize this json to an object that contains a Map (and the map contains litteral values and other maps). Assuming you have a bean similar to :
class MyBean {
int status;
Map<String, Object> result;
}
MyBean myBean = new Gson().fromJson(jsonString, MyBean.class);
It should work with no modification. Note that if the type of status is not a number I'm not sure Gson does the conversion as in the json string the value is quoted, same thing applies to your "age" property.
You can also have a look at Genson library http://code.google.com/p/genson/ it has most Gson features, other ones that no other library provide and has better performances. Have a look at the wiki http://code.google.com/p/genson/wiki/GettingStarted.
EDIT
Are the names really things like object1_1, object2_1 etc? When looking at the structure I imagine that object1 goes with object2 and so long. If you use gson you can write a custom TypeAdapter http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/TypeAdapter.html.
So you can create a root object similar to
class Response {
int status;
List<MyObject> result;
}
class MyObject {
String name;
int age;
String event;
String date;
}
In the read method of your TypeAdapter you should compose instances of MyObject based on the keys (object1 with object2, object1_1 with object2_1...) or take a similar approach.
If you want more details on how to do that you can also ask on Gson google group.

How to parse this JSON object

This is the json response from my server . How can i parse it and store it in HashMap? Please help me.
{'records':
[{
'number':165,
'description': 'abcd'
},
{
'number':166,
'description': 'ab'
},
{
'number':167,
'description': 'abc'
}]
}
im new in android but maybe you can do something like this:
JSONObject JsonObject = new JSONObject(json);
JSONArray JsonArray_ = JsonObject .getJSONArray("records");
for (int i = 0; i < numberOfItems; i++) {
JSONObject record= JsonArray_photo.getJSONObject(i);
parsedObject.number = record.getString("number"); //its the same for all fields
map.add(parsedObject);
}
I done something like that for my own JSON parser. hope this helps. cheers
I suggest you look at the gson library, which makes it very easy indeed to parse JSON into an object representing the data. So you could create a Record object, with public member variables for number, description, and then use gson to parse the JSON into an object array.
http://code.google.com/p/google-gson/
Add the .jar to your libs folder and then use it like this:
Record[] records = new GsonBuilder().create().fromJson(jsonString,Record[].class)
int number = record[0].number;
The org.json package is included in Android: http://developer.android.com/reference/org/json/package-summary.html
Use is simple:
JSONObject json_object = new JSONObject(String json_string);
Each property can then be accessed as a Java property, e.g. json_object.property. It will throw a JSONException if the parsing fails for some reason (i.e., invalid JSON).
You can use Gson library, you can find full tutorial on softwarepassion.com

Categories

Resources