Convert Java String to Json - java

I have a list of String which I wish to convert to Json. I am using org\json\me in order to do so. However, I don't know how to continue from here. A little help will be appreciated. Thanks.
This is my code:
public class PhoneData implements JSONAble {
private Display display;
private Form mainScr;
public PhoneData() {
mainScr = new Form("Phone Data");
String imei = IDENInfo.imeiToString(IDENInfo.getIMEI());
String imsi = new String();
try{
imsi=GPRSInfo.imeiToString(SIMCardInfo.getIMSI(), false );
}catch(SIMCardException ioe){}
String majorOS = DeviceInfo.getPlatformVersion();
int content = CodeModuleManager.getModuleHandle("net_rim_bb_phone_api");
String version = CodeModuleManager.getModuleVersion(content); //DeviceInfo.getSoftwareVersion();
String modelnumber = DeviceInfo.getDeviceName(); //get modelnumber
String [] phoneData = new String[] { modelnumber = "Model Number", majorOS = "majorOS", version = "softwareversion"
,imei = "imei", imsi = "imsi"}; // an Array
}
protected void startApp() throws MIDletStateChangeException {
// TODO Auto-generated method stub
display.setCurrent(mainScr);
PhoneData user = new PhoneData();
}
public void fromJSON(String jsonString) {
// TODO Auto-generated method stub
}
public String toJSON() {
// TODO Auto-generated method stub
return null;
}
}

You'll have to put your data inside a Vector, then use the new JSONArray(yourvector) to make a JSONArray.

Unless you specifically want to use org.json's barebones package, maybe have a look at this question.

You could use the Jettison driver with XStream to serialize / deserialize string <-> json :
http://x-stream.github.io/json-tutorial.html
I had used this sometime back - there are some caveats on how the json schema should be for the parser to parse perfectly well.

Related

storing an JSON array in java code array in android

I want to store the json array sent by php code in java array in android. My php code is working perfectly fine but in the app I get name: as the output. I want to display the names in the texview for checking purpose. Also I want to work with the namesby accessing them one by one.
Php code:
echo json_encode(array("result"=>$result));
Java code:
public class Salary {
public static final String DATA_URL1 = "http://********.com/name.php?salary=";
public static final String KEY_name = "name";
public static final String JSON_ARRAY1 = "result";
}
This is a method of my Name.java
private void showJSON(String response) {
String name = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Salary.JSON_ARRAY1);
for (int i = 0; i < result.length(); i++) {
JSONObject collegeData = result.getJSONObject(i);
name = collegeData.getString(Salary.KEY_name);
}
} catch (JSONException e) {
e.printStackTrace();
}
textViewResult1.setText("Name:\t" + name);
}
Use GSON Library
ArrayList<Salary> salaryArrayList = new ArrayList<>();
try {
salaryArrayList = new Gson().fromJson(response, new TypeToken<Salary>() {}.getType());
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
Then use salaryArrayList to get values.
Download GSON jar from this link

How to load ArrayList data into ListView using Android?

I am trying to create JSON data store into ArrayList and load on ListView. Now I have successfully stored my JSON data into ArrayList. But the problem is I have maintaining multiple column listview. I need to List out my first array on first column.
Below I have tried something, multiple columns with array. But exactly I dont know how to do that. Please help me, I am new developer for Android.
// I need to add my array into first column
private ArrayList<String> myarray = new ArrayList<String>();
//JSON string data's I have loaded
myarray.add(jsondata);
//LISTVIEW WATCHLIST
ListView listView=(ListView)findViewById(R.id.listView1);
list=new ArrayList<HashMap<String,String>>();
HashMap<String,String> temp=new HashMap<String, String>();
temp.put(FIRST_COLUMN, "Minchu");
temp.put(SECOND_COLUMN, "USA");
temp.put(THIRD_COLUMN, "City");
temp.put(FOURTH_COLUMN, "Ranks");
list.add(temp);
.
.
.
.
ListViewAdapters adapter=new ListViewAdapters(this,list);
listView.setAdapter(adapter);
NOTE : Above HashMap to putted manual data. I need to load first array first columns, second array second columns.
You need to create model for your json object see below code.
import java.io.Serializable;
public class PersonDetailsItem implements Serializable {
public int id;
private String intEducationEN, intVillageID;
public PersonDetailsItem(int id, String name, String phoneNo, String email) {
// TODO Auto-generated constructor stub
this.id = id;
this.strNameEN = name;
this.strEmailid = email;
}
public String getIntVillageID() {
return intVillageID;
}
public void setIntVillageID(String intVillageID) {
this.intVillageID = intVillageID;
}
public String getIntEducationEN() {
return intEducationEN;
}
public void setIntEducationEN(String intEducationEN) {
this.intEducationEN = intEducationEN;
}
public PersonDetailsItem() {
// TODO Auto-generated constructor stub
}
Then set the value for the model form parsing json received string.
private void parseJson(String rs) {
private ArrayList<PersonDetailsItem> listData = new ArrayList<PersonDetailsItem>();;
// TODO Auto-generated method stub
listData = new ArrayList<PersonDetailsItem>();
spinerPersonData = new ArrayList<SpinerItem>();
try {
JSONObject obj = new JSONObject(rs);
JSONArray jArray = obj.getJSONArray("Table");
for (int i = 0; i < jArray.length(); i++) {
JSONObject c = jArray.optJSONObject(i);
String intEducationEN = c.getString("intEducationEN");
String intVillageID = c.getString("intVillageID");
PersonDetailsItem personItem = new PersonDetailsItem();
personItem.setIntEducationEN(intEducationEN);
personItem.setIntVillageID(intVillageID);
listData.add(personItem);
}
} catch (JSONException e) { // TODO Auto-generated catch block
e.printStackTrace();
Log.v("perosnJson Error", e.toString());
}
}
set to listadapter
CustomAdapter adapter = new CustomAdapter(MainActivity.this, R.id.listView1, listData);
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
enter code here
You can check link for more detail https://github.com/yagneshshinde101/mysamaj/blob/master/MySamaj/src/com/example/mysamajmain/MainActivity.java

URL Transformer

I want to make a class in Java called URLTransformer.
Let's say I have a blog entry and want to format my text (e.g. because some words are in Swedish).
This is my code right now:
public class URLTransformer {
public static void main(String[] args) {
String basurl = "http://www.mybloggsys.com/user_abc/";
String[] rubriker = {
"Nu Kommer Vintern till aland",
"Onskningar ar nagot man vill uppna",
"Just English Letters"
};
for (String rubrik : rubriker) {
String rubrik2=rubrik.toLowerCase().replace(" ", "_").replace("Å", "a").replace("å", "a").replace("ä", "a").replace("Ö", "o");
URLTransformer transformer = new URLTransformer();
URLTransformer(basurl, rubrik2);
String url = transformer.getURL();
String aElement = transformer.getAElement();
System.out.println(rubrik2);
System.out.println(url);
System.out.println(aElement);
}
URLTransformer transformer = new URLTransformer();
}
private String getAElement() {
// TODO Auto-generated method stub
return null;
}
private String getURL() {
// TODO Auto-generated method stub
return null;
}
private static void URLTransformer(String basurl, String rubrik2) {
// TODO Auto-generated method stub
}
}
Now, I can get Eclipse to execute this code but I get a lot of "Null" messages. Is it possible to not get it or does it even matter after compiling my code? In my homework task, the final code should look exactly like this:
Nu kommer Vinter till Åland
http://www.mybloggsys.com/user_abc/nu_kommer_vintern_till_aland
Nu Kommer Vintern till Åland
Önskningar är något man vill uppnå
(url link)/onskningar_ar_nagot_man_vill_uppna
Önskningar är något man vill uppnå
Just English Letters
(url link)/just_english_letters
Just English Letters
Any help will be greatly appreciated, it feels like it almost works just this </a> element thing and null messages that are left.
Here is the code for you:
public class URLTransformer {
private String baseurl;
private String baseString;
// Constructor of the class that uses a base url and a base string
public URLTransformer(String baseurl, String baseString) {
super();
this.baseurl = baseurl;
this.baseString = baseString;
}
// Method that return the href calculated
private String getHref() {
// transform the string to remove non english characters with _ instead of spaces
return baseurl + baseString.toLowerCase().replace(" ", "_").replace("Å", "a").replace("å", "a").replace("ä", "a").replace("Ö", "o");
}
// return a <a> link with a call to the href link method
private String getAElement() {
StringBuilder aElement = new StringBuilder();
aElement.append("<a href=\"");
aElement.append(getHref());
aElement.append("\">");
aElement.append(baseString);
aElement.append("</a>");
return aElement.toString();
}
public static void main(String[] args) {
String basurl = "http://www.mybloggsys.com/user_abc/";
String[] rubriker = { "Nu Kommer Vintern till aland", "Onskningar ar nagot man vill uppna", "Just English Letters" };
// iterate over the
for (String rubrik : rubriker) {
URLTransformer transformer = new URLTransformer(basurl, rubrik); // creation of the class object that is able to make a link from the string
System.out.println(rubrik); // prints the provided string
System.out.println(transformer.getHref()); // use of the getHref method to get an url from the string
System.out.println(transformer.getAElement()); // display of the <a> element
}
}
}
Note : I've added comments to the code and see my comment below to have explanations on what was wrong with the provided code.

Hive UDTF returning ArrayList Column

I am new to Hive UDTF. I have a requirement where I have to pass string values as Paratmeter in UDTF and the returning Column should be a ArrayList.
I have written the following Code:
public StructObjectInspector initialize(ObjectInspector[] arg0)
throws UDFArgumentException {
ArrayList<String> fieldNames = new ArrayList<String>();
ArrayList<ObjectInspector> fieldOIs = new ArrayList<ObjectInspector>();
fieldNames.add("col1");
stringOI = (PrimitiveObjectInspector) arg0[0];
listOi=(ListObjectInspector) arg0[0];
fieldOIs.add(listOi.getListElementObjectInspector());
return ObjectInspectorFactory.getStandardStructObjectInspector(fieldNames, fieldOIs);
}
#Override
public void process(Object[] record) throws HiveException {
// TODO Auto-generated method stub
String document = (String) stringOI.getPrimitiveJavaObject(record[0]);
if (document == null) {
return;
}
firstColumn=(String) stringOI.getPrimitiveJavaObject(record[0]);
secondColumn=(String) stringOI.getPrimitiveJavaObject(record[1]);
if(outputMapper.containsKey(firstColumn))
{
ArrayList<String> tempList=new ArrayList<String>();
tempList=outputMapper.get(firstColumn);
tempList.add(secondColumn);
outputMapper.put(firstColumn,tempList);
}
else
{
childVendorList=new ArrayList<String>();
childVendorList.add(secondColumn);
outputMapper.put(firstColumn,childVendorList);
}
forward(outputMapper.get(firstColumn));
}
}
And I am getting the following Exception:
java.lang.ClassCastException: org.apache.hadoop.hive.serde2.lazy.objectinspector.primitive.LazyStringObjectInspector cannot be cast to org.apache.hadoop.hive.serde2.objectinspector.ListObjectInspector
Can Anyone Help???
listOi=(ListObjectInspector) arg0[0];
fieldOIs.add(listOi.getListElementObjectInspector());
return ObjectInspectorFactory.getStandardStructObjectInspector(fieldNames, fieldOIs);
This arg0[0] is a primitive object inspector. With listOi.getListElementObjectInspector(), just get a similar PrimitiveObjectInspector(like String,Integer is not a List). It should
fieldOIs.add(ObjectInspectorFactory.getStandardListObjectInspector(stringOI ))
This will specific the output column with List of type of stringOI.

Java Boolean into Object[][]

I got following code and there is this error (I tried to keep the code as short as possible, ignore the getColumnCount etc. functions just the constructor):
The following code is used to make a JTable in Swing by an SQLite statement, I need the booleans for checkboxes (Yes I know I have to edit/add an function, but I wanted to keep the code as small as possible).
Code:
package view;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.table.AbstractTableModel;
import controller.Database;
class Test extends AbstractTableModel {
Database db = new Database();
ResultSet rs;
private String[] columnNames = {"Vorname", "Nachname", "E-Mail", "Anrede", "Jahrgang", "Ablösung", "Scheibe", "Waffe", "Gruppe", "Verpflegung", "Aktiv"};
Object[][] data;
public Test(){
int result = 0;
try {
rs = db.stat.executeQuery("select count(*) as schuetzencount from schuetze;");
result = Integer.parseInt(rs.getString("schuetzencount"));
data = new String[result][11];
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
rs = db.stat.executeQuery("select * from schuetze as s join waffe as w on w.Waffe_ID = s.Waffe_ID join gruppe as g on g.Gruppe_ID = s.Gruppe_ID join anrede as a on a.Anrede_ID = s.Anrede_ID join verpflegung as v on v.Verpflegung_ID = s.Verpflegung_ID;");
int counter = 0;
while(rs.next()){
data[counter][1] = rs.getString("Schuetze_Nachname");
data[counter][0] = rs.getString("Schuetze_Vorname");
data[counter][4] = rs.getString("Schuetze_Jahrgang");
data[counter][2] = rs.getString("Schuetze_Email");
data[counter][5] = rs.getString("Schuetze_Abloesung");
data[counter][6] = rs.getString("Schuetze_Scheibe");
data[counter][7] = rs.getString("Waffe_Name");
data[counter][8] = rs.getString("Gruppe_Name");
data[counter][3] = rs.getString("Anrede_Name");
data[counter][9] = rs.getString("Verpflegung_Name");
data[counter][10] = true;
counter++;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public int getColumnCount() {
// TODO Auto-generated method stub
return 0;
}
#Override
public int getRowCount() {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object getValueAt(int arg0, int arg1) {
// TODO Auto-generated method stub
return null;
}
public static void main(String[] args) {
Test t = new Test();
}
}
Error:
Exception in thread "main" java.lang.ArrayStoreException: java.lang.Boolean
at view.Test.<init>(Test.java:43)
at view.Test.main(Test.java:72)
If I'll do
Object[][] data = {{"Test", "Test","Test","Test","Test","Test","Test","Test","Test","Test",true}}
it works, but that's not what I need. Then I tried to do a Object[] and fill the Booleans in and then add the Object[] into the data[][] but this also didn't work.
I hope someone can help me, thanks.
Greetz.
You have Array of Strings and try to put Boolean there in line
data[counter][10] = true;
That is not allowed.
When You do
Object[][] data = {{"Test", "Test","Test","Test","Test","Test","Test","Test","Test","Test",true}}
Java creates for you array of Objects
Like:
Object[][] o = new Object[1][6];
o[0][2] = true; // it works
Your array expects a String as dataType, on the other hand are you trying to put a boolean into it.
data[counter][10] = true;
a simple solution to this is using a string "true"instead of the primitive booleantype (or parse it to string)
data[counter][10] = "true";
You cannot insert a boolean value to an array of String. That is the problem :
data = new String[result][11];
data[counter][10] = true;
At least insert it as a String and parse it when neccessary.
You have defined data as matrix of Objects, but instantiated it as matrix of String.
That's why, at runtime, you have this type mismatch exception.
Either instantiate it like:
Object[][] o = new Object[1][6];
or
replace boolean value with string:
data[counter][10] = "true";
The problem is here:
data = new String[result][11];
You declare the array of String and you do this
data[counter][10] = true;
You have two options:
declare data as
new Object[result][11];
put string instead of boolean
data[counter][10] = Boolean.TRUE.toString();

Categories