I have a Sring s (JSON array) [{"Phonetype":"Pre","Phone":"918282311"},{"Phonetype":"pre","Phone":"918333222"}]
and now i want to convert this string to JSON array of the JSON objects.
in my code i only can create a JSONrray of objects...
#Override
public ArrayList<TelephoneNumber> convertToAttribute(String s) {
ArrayList<TelephoneNumber> list = new ArrayList<TelephoneNumber>();
JSONParser parser = new JSONParser();
JSONArray arr = null;
try {
arr = (JSONArray) parser.parse(s);
}
catch (ParseException e) {
e.printStackTrace();
}
for (JSONObject jo: arr)
{
System.out.println("obj " +jo.get("Phone");
}
//create a list
return list;
}
how create a JsonArray of JsonObjects?
Consider using Gson to parse json values and use FieldNamingPolicy on a GsonBuilder to get a Gson object that handles upper camel case names correctly:
Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
.create();
Type listType = new TypeToken<ArrayList<TelephoneNumber>>() {}.getType();
List<TelephoneNumber> numbers = gson.fromJson(jsonArray, listType);
I'd recommend taking a look at Gson. It is a series of Java classes written by The Google Overlords that handles serializing and deserializing JSON from and to Java classes.
So, making a few assumptions about what your TelephoneNumber class looks like, you should be able to do this:
Type listType = new TypeToken<ArrayList<TelephoneNumber>>() {
}.getType();
ArrayList<TelephoneNumber> yourList = new Gson().fromJson(s, listType);
Then return yourList....
Related
strResponse = {"GetCitiesResult":["1-Vizag","2-Hyderbad","3-Pune","4-Chennai","9-123","11-Rohatash","12-gopi","13-Rohatash","14-Rohatash","10-123"]}
JSONObject json = new JSONObject(strResponse);
// get LL json object
String json_LL = json.getJSONObject("GetCitiesResult").toString();
Now i want to convert the json string to List in andriod
Please make sure your response String is correct format, if it is, then try this:
try {
ArrayList<String> list = new ArrayList<String>();
JSONObject json = new JSONObject(strResponse);
JSONArray array = json.getJSONArray("GetCitiesResult");
for (int i = 0; i < array.length(); i++) {
list.add(array.getString(i));
}
} catch (Exception e) {
e.printStackTrace();
}
Simply using Gson library you can convert json response to pojo class.
Copy the json string to create pojo structure using this link: http://www.jsonschema2pojo.org/
Gson gson = new Gson();
GetCitiesResult citiesResult = gson.fromJson(responseString, GetCitiesResult.class);
It will give the GetCitiesResult object inside that object you get a list of your response like
public List<String> getGetCitiesResult() {
return getCitiesResult;
}
Call only citiesResult.getGetCitiesResult(); it will give a list of cities.
You can also use this library com.squareup.retrofit2:converter-gson:2.1.0
This piece of code did the trick
List<String> list3 = json.getJSONArray("GetCitiesResult").toList()
.stream()
.map(o -> (String) o)
.collect(Collectors.toList());
list3.forEach(System.out::println);
And printed:
1-Vizag
2-Hyderbad
3-Pune
4-Chennai
9-123
11-Rohatash
12-gopi
13-Rohatash
14-Rohatash
10-123
below is code:
private void parse(String response) {
try {
List<String> stringList = new ArrayList<>();
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("GetCitiesResult");
for (int i=0; i <jsonArray.length(); i++){
stringList.add(jsonArray.getString(i));
}
Log.d ("asd", "--------"+ stringList);
} catch (Exception e) {
e.printStackTrace();
}
}
Hope it will help.
Output is when print list :
--------[1-Vizag, 2-Hyderbad, 3-Pune, 4-Chennai, 9-123, 11-Rohatash, 12-gopi, 13-Rohatash, 14-Rohatash, 10-123]
Ok you must know first something about JSON
Json object is be {// some attribute}
Json Array is be [// some attribute]
Now You have
{"GetCitiesResult":["1-Vizag","2-Hyderbad",
"3-Pune","4-Chennai","9-123","11-Rohatash",
"12-gopi","13-Rohatash","14-Rohatash","10-123"]}
That`s Means you have JSON array is GetCitiesResult
which have array of String
Now Try this
JSONObject obj = new JSONObject(data);
JSONArray loadeddata = new JSONArray(obj.getString("GetCitiesResult"));
for (int i = 0; i <DoctorData.length(); i++) {// what to do here}
where data is your String
I am a beginner with JAVA and are using the gson library to convert a JSON string something like this:
String json = "{\"Report Title\": \"Simple Embedded Report Example with Parameters\",\"Col Headers BG Color\": \"yellow\",\"Customer Names\":[\"American Souvenirs Inc\",\"Toys4GrownUps.com\",\"giftsbymail.co.uk\",\"BG&E Collectables\",\"Classic Gift Ideas, Inc\"]}";
Gson gson = new Gson();
jsonObject (Map) = gson.fromJson(json, Object.class);
But the problem is I need the "Customer Names" array to be returned as a string array and not an object array.
Can gson do this or would it have to be converted afterwards by somehow detecting the type (array) and then looping over each element converting it to a string array and replacing the object array ?
The added problem is that the JSON field names are not fixed, and there may be multiple arrays contained in the JSON string and all of them need converting.
you can use jsonarray to get specific field
you can find json api JSON
add json text into file or you can use buffer to pass to parameter
String json = "{\"customer_names\" : [...]}";
then
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("test.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray msg = (JSONArray) jsonObject.get("Customer Names");
Iterator<String> iterator = msg.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
or you can use GSON something like this
public class JsonPojo {
private String[] customer_names;
public String[] getCustomerNames(){ return this.customer_names;}
}
public class App{
public static main(String[] args) {
Gson gson = new Gson();
JsonPojo thing = gson.fromJson(json, JsonPojo.class);
if (thing.getCustomerNames()!= null)
{
// do what you want
}
}
}
I have a Array with some value
when i store that array i got result like this
[{"id":56678,"Name":"Rehman Agarwal"},{"id":66849,"Name":"Rasul Guha"}]
means in a single line.
but I just want to get output like
[{"id":56678,"Name":"Rehman Agarwal"},
{"id":66849,"Name":"Rasul Guha"}]
new line after JSON object ..
How to do it ?
EDIT : i use JSONObject && JSONArray for create json Object and array respectively
Using gson library you can pretty print your json strings like below -
public static String toPrettyFormat(String jsonString) {
JsonParser parser = new JsonParser();
JsonObject json = parser.parse(jsonString).getAsJsonObject();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String prettyJson = gson.toJson(json);
return prettyJson;
}
And call it like below -
public void testPrettyPrint() {
String compactJson = "{\"playerID\":1234,\"name\":\"Test\",\"itemList\":[{\"itemID\":1,\"name\":\"Axe\",\"atk\":12,\"def\":0},{\"itemID\":2,\"name\":\"Sword\",\"atk\":5,\"def\":5},{\"itemID\":3,\"name\":\"Shield\",\"atk\":0,\"def\":10}]}";
String prettyJson = toPrettyFormat(compactJson);
System.out.println("Compact:\n" + compactJson);
System.out.println("Pretty:\n" + prettyJson);
}
This question already has answers here:
Convert a JSON string to object in Java ME?
(14 answers)
Closed 8 years ago.
i need to convert this String JSON to a Java Object:
{"estabelecimento":[{"id":"5","idUsuario":"5","razaoSocial":"Bibi LTDA","nomeFantasia":"BibiPizza","telefone":"22121212","email":"ronaldo#bibi.com","gostaram":"0"},{"id":"8","idUsuario":"1","razaoSocial":"Nestor Latuf LTDA","nomeFantasia":"Nestor Sorvetes","telefone":"32343233","email":"nestor#Sorvete.com","foto":"","gostaram":"0"},{"id":"9","idUsuario":"1","razaoSocial":"Comercio Alimenticio Rivaldo","nomeFantasia":"Rogers Burguer","telefone":"210021020","email":"roger#gmail.com","foto":"","gostaram":"0"}]}
I try this, but not work:
//JSONArray jArr = new JSONArray(br.toString());
//JSONObject jObj = new JSONObject(br.toString());
//JSONArray jArr = jObj.getJSONArray("list");
JSONArray jArr = new JSONArray(br.toString());
for (int i=0; i < jArr.length(); i++) {
JSONObject obj = jArr.getJSONObject(i);
estabelecimento.setId(obj.getLong("id"));
estabelecimento.setIdUsuario(obj.getLong("idUsuario"));
estabelecimento.setRazaoSocial(obj.getString("razaoSocial"));
estabelecimento.setNomeFantasia(obj.getString("nomeFantasia"));
estabelecimento.setTelefone(obj.getString("telefone"));
estabelecimento.setEmail(obj.getString("email"));
estabelecimento.setGostaram(obj.getInt("gostaram"));
estabelecimentoList.add(estabelecimento);
}
con.disconnect();
How can i obtain a Java Object? Someone can help? tks.
You can use the Gson lib of google:
public class MyClass {
private int data1 = 100;
private String data2 = "hello";
private List<String> list = new ArrayList<String>() {
{
add("String 1");
add("String 2");
add("String 3");
}
};
//getter and setter methods needed
}
String str = {"data1":100,"data2":"hello","list":["String 1","String 2","String 3"]};
com.google.gson.Gson gson = new com.google.gson.Gson();
//To convert json string to class use fromJson
MyClass obj = gson.fromJson(str, MyClass .class);
//To convert class object to json string use toJson
String json = gson.toJson(obj);
At high level two major steps:
Generate a Java class from your JSON, e.g. by using this generator or similar: http://www.jsonschema2pojo.org/
Use Jackson processor to deserialize your JSON file:
ObjectMapper mapper = new ObjectMapper();
YourGeneratedClass obj = (YourGeneratedClass) mapper.readValue(new File("path-to-your-json-file"), YourGeneratedClass.class);
More about Jackson: http://jackson.codehaus.org/
You can also create YourGeneratedClass manually if you feel comfortable enough with this.
Please advice how to convert a String to JsonObject using gson library.
What I unsuccesfully do:
String string = "abcde";
Gson gson = new Gson();
JsonObject json = new JsonObject();
json = gson.toJson(string); // Can't convert String to JsonObject
You can convert it to a JavaBean if you want using:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
gson.fromJson(jsonString, JavaBean.class)
To use JsonObject, which is more flexible, use the following:
String json = "{\"Success\":true,\"Message\":\"Invalid access token.\"}";
JsonParser jsonParser = new JsonParser();
JsonObject jo = (JsonObject)jsonParser.parse(json);
Assert.assertNotNull(jo);
Assert.assertTrue(jo.get("Success").getAsString());
Which is equivalent to the following:
JsonElement jelem = gson.fromJson(json, JsonElement.class);
JsonObject jobj = jelem.getAsJsonObject();
To do it in a simpler way, consider below:
JsonObject jsonObject = (new JsonParser()).parse(json).getAsJsonObject();
String string = "abcde"; // The String which Need To Be Converted
JsonObject convertedObject = new Gson().fromJson(string, JsonObject.class);
I do this, and it worked.
You don't need to use JsonObject. You should be using Gson to convert to/from JSON strings and your own Java objects.
See the Gson User Guide:
(Serialization)
Gson gson = new Gson();
gson.toJson(1); // prints 1
gson.toJson("abcd"); // prints "abcd"
gson.toJson(new Long(10)); // prints 10
int[] values = { 1 };
gson.toJson(values); // prints [1]
(Deserialization)
int one = gson.fromJson("1", int.class);
Integer one = gson.fromJson("1", Integer.class);
Long one = gson.fromJson("1", Long.class);
Boolean false = gson.fromJson("false", Boolean.class);
String str = gson.fromJson("\"abc\"", String.class);
String anotherStr = gson.fromJson("[\"abc\"]", String.class)
String emailData = {"to": "abc#abctest.com","subject":"User details","body": "The user has completed his training"
}
// Java model class
public class EmailData {
public String to;
public String subject;
public String body;
}
//Final Data
Gson gson = new Gson();
EmailData emaildata = gson.fromJson(emailData, EmailData.class);
Looks like the above answer did not answer the question completely.
I think you are looking for something like below:
class TransactionResponse {
String Success, Message;
List<Response> Response;
}
TransactionResponse = new Gson().fromJson(response, TransactionResponse.class);
where my response is something like this:
{"Success":false,"Message":"Invalid access token.","Response":null}
As you can see, the variable name should be same as the Json string representation of the key in the key value pair. This will automatically convert your gson string to JsonObject.
Gson gson = new Gson();
YourClass yourClassObject = new YourClass();
String jsonString = gson.toJson(yourClassObject);
Note that as of Gson 2.8.6, instance method JsonParser.parse has been deprecated and replaced by static method JsonParser.parseString:
JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject();
JsonObject jsonObject = (JsonObject) new JsonParser().parse("YourJsonString");
if you just want to convert string to json then use:
use org.json: https://mvnrepository.com/artifact/org.json/json/20210307
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20210307</version>
</dependency>
import these
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;
Now convert it as
//now you can convert string to array and object without having complicated maps and objects
try {
JSONArray jsonArray = new JSONArray("[1,2,3,4,5]");
//you can give entire jsonObject here
JSONObject jsonObject= new JSONObject("{\"name\":\"test\"}") ;
System.out.println("outputarray: "+ jsonArray.toString(2));
System.out.println("outputObject: "+ jsonObject.toString(2));
}catch (JSONException err){
System.out.println("Error: "+ err.toString());
}
You can use the already Gson existing method :
inline fun <I, reified O> I.convert():O {
val json = gson.toJson(this)
return gson.fromJson(json, object : TypeToken<O>() {}.type)
}