suppose I have {"data": {"243232": {"id": "testid","name": "test" } }}
so how to get correct value thanks.
you cant directly pass above String with Gson as "243232" is number and we cant declare variable which start from number, So for parsing this you must modify the string with some notification
i.e. {"data": {"temp243232": {"id": "testid","name": "test" } }}
here i modified string manually "243232" by "temp243232", now you can parse it
You can use a JSON parser for Java like Google GSON. This works best if the class whose object your data in json represents, is known to you.
String str = ""; //contains your json string
Gson gson = new Gson();
MyClass var = gson.fromJson(str,MyClass.class);
where MyClass will be a class which represents the object.
Then you can access data just like you'd do from a data structure in your program, it'll be something like var.data.
Related
I want to send this parameter in request and tried to send a simple array list but that was not working
"Language": [
"string","string","string"
]
If "Language" is key and ["string1","string2","string3"] is value then create method in interface as below.
#FormUrlEncoded
#POST(LINK_API)
Call<ResponseModel> getResponse(#Field("Language") String languageArray);
and call it using interface instance like this :
JSONArray languageArray = new JSONArray();
languageArray.add("string1");
languageArray.add("string2");
languageArray.add("string3");
String langArray = languageArray.toString();
Call<ResponseModel> responseModel = apiObject.getResponse(langArray);
responseModel.enqueue(...);
This will work perfectly.
try post query with field parameter as string..
convert your jsonObject to String using,
String b = json_object.toString();
At Server Side, convert string back to JsonObject or whatever else you need.
This is my JSON response:
{
"email":[
"This field must be unique."
]
}
I want to retrieve the value of json object email and display it. I tried using Gson but always getting null. Created a model class with email variable with type JSONArray -- still no luck.
Thanks in advance .
Note that the email attribute is actually an array of strings.
The object to be deserialized by Gson should look like the following:
public class Response {
#SerializedName("email")
public List<String> emails;
}
Then using gson
Response response = gson.fromJson(json, Response.class);
And then you can access to that object by doing
response.emails.get(0)
I have a JSON Like this
{ "video":{
"video_3745":{ },
"video_3437":{ },
"video_3471":{ },
"video_4114":{ }
}
}
In which every "video_xxxx" is of the SAME type. Is there a way to treat the "video" field as an array of that type? I need to iterate over all the videos, but the API is not sending them in an array, and I don't know how to model a class to receive this JSON without having to manually specify all the field names...
does GSON or LoganSquare have anything to help me out with this?
Try something like this
JSONObject video= json.getJSONObject("video"); // json is the whole response
Iterator x = video.keys();
JSONArray jsonArray = new JSONArray();
while (x.hasNext()){
String key = (String) x.next();
jsonArray.put(video.get(key));
}
You can't treat them as an array, but with the org.json.JSONObject class you can get the list of keys and iterate over them. I believe in GSON the JsonObject.entrySet method will allow something similar.
https://developer.android.com/reference/org/json/JSONObject.html
https://google.github.io/gson/apidocs/com/google/gson/JsonObject.html
I am using GSON Library to parse my JSON tag.
some of the tags are expected to hold string values (not arrays). the problem is, sometimes the element is empty [] and when it does that the console gives me this error
expected String but was BEGIIN ARRAY.
The following is the ideal case for my JSON
{
"internet": "600.00",
"internet_remarks": "Fibre 1gbps",
}
but sometimes it becomes
{
"internet": "600.00",
"internet_remarks": [],
}
My parsing code is as follows:
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
MainContainer mainContainer = gson.fromJson(obj, MainContainer.class);
while in my class is as follows the varailbas are defined as follows
private String internet;
private String internet_remarks;
My question is what changes should i make so that the variable accommodate the empty array []
If you don't control the source of the (poorly designed) JSON and can't fix it, then you're going to need to write a custom deserializer that constructs your MainContainer object.
See: How do I write a custom deserializer? here on SO and/or the information in the Gson User's guide
If the only time that field is an array type is when it's an empty array, the easiest approach I can think of is simply inspecting the returned JSON and if it's an array, remove it. Then deserialize to your MainContainer. Gson silently ignores any missing elements in the JSON and internet_remarks will be null in your MainContainer.
class MyDeserialier implements JsonDeserializer<MainContainer>
{
#Override
public MainContainer deserialize(JsonElement je, Type type,
JsonDeserializationContext jdc)
throws JsonParseException
{
JsonObject obj = je.getAsJsonObject();
if (obj.get("internet_remarks").isJsonArray())
{
obj.remove("internet_remarks");
}
return new Gson().fromJson(obj, MainContainer.class):
}
}
If that's not actually the case and that array might not be empty, you'll need to add the logic to deal with that and convert it to a String if that's what you really want.
In your case:
The gson parser is confused when you are asking it to parse an array into string.
So, you can change the internet_remarks into an array of string.
Its always a safe approach to use annonations in the container class.
Extras:
When ever you are working with json, these two tools will be handy.
1.OnlineJsonEditor.
2.JsonGen
I would suggest declare your second attribute as an array. i.e.
private String[] internet_remarks;
When you have a single string, still put it in the array.
eg:
{
"internet": "600.00",
"internet_remarks": ["Fibre 1gbps"]
}
When it's empty,
{
"internet": "600.00",
"internet_remarks": []
}
So your json will always be consistent.
Also, I noted that you're not really making use of the GsonBuilder. You could just create the Gson instance with a constructor than a builder.
Gson gson = new Gson();
Okay I am quering data from a Grails webservice that returns JSON. The JSON when viewed with the JSONViewer app parses fine. When I take that same string and use JSONObject(string) in my Android app I get "value of String cannot be converted to JSONObject."
Here's my JSON string
[[{"class":"mygrails.TopTen","id":491,"ttAmount":14200000,"ttMlId":402,"ttRank":1,"ttWeekId":1108},{"class":"mygrails.MovieList","id":402,"mlApproved":1,"mlApprovedId":5,"mlMovieId":"GNOMEOAN","mlReleaseDate":"2011-03-08T07:41:45Z","mlTitle":"Gnomeo and Juliet","mlWeekId":1106}]]
Now the JSON is comes from the standard JSON conversion of a SQL data using render from the groovy file through the import grails.converters.JSON.
... //(call to render JSON in the groovy file)
def a
a = Table.findAll("from someTable as st where st.id=" params.id)
render a as JSON
...
So I am not sure what I doing wrong and why the JSON looks a little off to me. (still new to JSON)
In json if you see "[]" means its a json array and if you see "{}" it is an json object. Both of then can have the other nested inside then.
In your case the string the starts with json array.
So try something like the following
String str = "[[{"class":"mygrails.TopTen","id":491,"ttAmount":14200000,"ttMlId":402,"ttRank":1,"ttWeekId":1108},{"class":"mygrails.MovieList","id":402,"mlApproved":1,"mlApprovedId":5,"mlMovieId":"GNOMEOAN","mlReleaseDate":"2011-03-08T07:41:45Z","mlTitle":"Gnomeo and Juliet","mlWeekId":1106}]]";
JSONArray jsonArray = new JSONArray(str);
jsonArray = jsonArray.getJSONArray(0);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String class = jsonObject.getString("class"); // class will value "mygrails.TopTen"
Try to create an JSONArray from the String instead of JSONObject. I didn't test this but that should do the trick: you have two nested arrays that contain then actual data.
Check out your JSON online with http://jsonformat.com/
http://www.freeformatter.com/json-formatter.html
JSON Viewer
http://jsonviewer.stack.hu/
Paste your text in there and you can see what you should parse: