Java converts an object to an instance of a string

Source: Internet
Author: User
Tags json object object string to json stub

Three ways to convert string types to Objects

First, the use of object.tostring ()

The ToString method is a public method of the Java.lang.Object object. Any object in Java inherits the object, so it is generally possible for any object to invoke the method of ToString. This is the way in which a common derived class overwrites the ToString () method in object.
However, when using this method, be aware that object is not a null value, or you will throw a NullPointerException exception.

Second, the use of (String) Object

The method is a standard type conversion method that converts object to string. However, in using this method it is important to note that the type that needs to be converted must be able to be converted to string, otherwise a Calsscastexception exception error occurs.


Object o = new Integer (100);
String string = (String) o;

This program code will appear Java.lang.ClassCastException:java.lang.Integer cannot be cast to java.lang.String. Because the integer type is cast to a string type, it cannot be passed.

Iii. string.valueof (Object)

We need to worry about the null problem when we use the Object.ToString () method. However, you do not need to worry about the null value problem with this method. Because when string.valueof (object) is used, it determines whether object is a null value and, if so, returns NULL. The following is the source code for string.valueof (Object):


public static String valueof (Object obj) {
return (obj = null)? "Null": obj.tostring ();

}


From the above we can see two points: first, there is no need to worry about the null problem. The second is that it is based on the ToString () method.
However, it is important to note that when object is null, the value of String.valueof (object) is a string object: "null" instead of null!!!


example,

The code is as follows Copy Code

Package test;
Class a{
int A;
int b;
public int Geta () {
return A;
}

public void SetA (int a) {
THIS.A = A;
}


public int Getb () {
return b;
}

public void Setb (int b) {
this.b = b;
}


}
public class Test {

public static void Main (String args[]) {
A A = new A ();
A.seta (8);
A.SETB (9);
System.out.println ("A.A:" +A.A);
System.out.println ("A.B:" +a.b);
System.out.println (a);
}
}

The results of the operation are:


A.a:8
A.b:9
Test. A@15093f1

As you can see, I was trying to output the values of a and B, but the third line of the result was not the result we wanted. Why, then?

Object has a method of ToString (), but unfortunately we need to rewrite this method in order to output according to our own will, the above program slightly modified, that is, add rewrite the ToString function code:

  code is as follows copy code


Package test;
Class a{
int A;
int b;
public int Geta () {
return A;
}

public void SetA (int a) {
THIS.A = A;
}


public int Getb () {
return b;
}

public void Setb (int b) {
this.b = b;
}

Public String toString () {
Return "A.A:" +a+ "; A.B: "+B;
}

}
public class Test {

public static void Main (String args[]) {
A A = new A ();
A.seta (8);
A.SETB (9);
System.out.println ("A.A:" +A.A);
System.out.println ("A.B:" +a.b);
System.out.println (a);
}
}

The results of the run are:


A.a:8
A.b:9
A.a:8; A.b:9


1. Simple parsing of JSON strings

First convert the JSON string to a JSON object, and then parse the JSON object, as follows.

The code is as follows Copy Code
Jsonobject jsonobject = Jsonobject.fromobject (JSONSTR);

Gets its value based on the key in the JSON

The code is as follows Copy Code

String name = jsonobject.getstring ("name");
int num = jsonobject.getint ("num");
String sex = jsonobject.getstring ("Sex");
int age = Jsonobject.getint (' age ');


2. Convert a JSON string to a Java object

The JSON string is also converted to a JSON object, and the JSON object is converted to a Java object, as shown below.

The code is as follows Copy Code
Jsonobject obj = new Jsonobject (). Fromobject (JSONSTR);//Convert JSON string to JSON object

Convert a JSON object to a Java object

The code is as follows Copy Code
person JB = (person) jsonobject.tobean (obj,person.class);//Convert a JSON object to a Person object


3. Convert Java objects to JSON strings

Converts a Java object to a JSON object before converting a JSON object to a JSON string

The code is as follows Copy Code

Jsonobject json = jsonobject.fromobject (obj);//Convert Java objects to JSON objects

String str = json.tostring ();//Convert JSON object to string

The complete code is as follows:

The code is as follows Copy Code

Package baz.parse;

Import java.util.ArrayList;
Import java.util.List;

Import Net.sf.json.JSON;
Import Net.sf.json.JSONArray;
Import Net.sf.json.JSONObject;
Import Net.sf.json.JSONSerializer;
Import Baz.bean.Person;

public class Parsejson {

Private String jsonstr;

Public Parsejson () {

}

Public Parsejson (String str) {
This.jsonstr = str;
}
/**
* Parse JSON string
*/
public void Parse () {
Jsonobject jsonobject = Jsonobject.fromobject (JSONSTR);
String name = jsonobject.getstring ("name");
int num = jsonobject.getint ("num");
String sex = jsonobject.getstring ("Sex");
int age = Jsonobject.getint (' age ');

SYSTEM.OUT.PRINTLN (name + "" + num + "" + Sex + "" + age);
}
Converts a JSON string to a Java object
Public Person Json2object () {
Receives the {} object where an array object is received with an exception
if (Jsonstr.indexof ("[")!=-1) {
Jsonstr = Jsonstr.replace ("[", "");
}
if (Jsonstr.indexof ("]")!=-1) {
Jsonstr = Jsonstr.replace ("]", "");
}
Jsonobject obj = new Jsonobject (). Fromobject (JSONSTR);//Convert JSON string to JSON object
person JB = (person) jsonobject.tobean (obj,person.class);//Convert a JSON object to a Person object
Return jb;//returns a Person object
}

}


Package Baz.bean;

public class Person {

private String name;
private int num;
Private String sex;
private int age;

Public person () {
TODO auto-generated Constructor stub
}

Public person (string name, int num, String sex, int age) {
Super ();
THIS.name = name;
This.num = num;
This.sex = sex;
This.age = age;
}

Public String GetName () {
return name;
}

public void SetName (String name) {
THIS.name = name;
}

public int Getnum () {
return num;
}

public void setnum (int num) {
This.num = num;
}

Public String Getsex () {
return sex;
}

public void Setsex (String sex) {
This.sex = sex;
}

public int getage () {
return age;
}

public void Setage (int age) {
This.age = age;
}

}


Converts a Java object to a JSON string

Package baz.cons;


Import Net.sf.json.JSONObject;


/**
* Convert Java objects to JSON strings
* @author Administrator
*
*/
public class Consjson {

Public Consjson () {
TODO auto-generated Constructor stub
}

Public String Object2json (Object obj) {
Jsonobject json = jsonobject.fromobject (obj);//Convert Java objects to JSON objects
String str = json.tostring ();//Convert JSON object to string

return str;
}
}
Test class:
Package baz.test;

Import java.util.List;

Import Baz.bean.Person;
Import Baz.cons.ConsJson;
Import Baz.parse.ParseJson;


public class Test {
 public static void Main (string[] args) {
  
  //Converts a string to J The Son object is then built according to the value
  parsejson PJ = new Parsejson ("{\ name\": \ "gu\", \ "num\": 123456,\ "sex\": \ "male\", \ " Age\ ": 24}");
  pj.parse ();
  
  //converts a JSON string to a Java object
  person p = pj. Json2object ();
  system.out.println ("Name:" + p.getname ());
  system.out.println ("Num:" + p.getnum ());
  system.out.println ("Sex:" + p.getsex ());
  system.out.println ("Age:" + p.getage ());
  
  //Converts a Java object to a JSON string
  person p1 = new Person ("GU1", 123, "male",);
  consjson CJ = new Consjson ();
  string str1 = CJ. Object2json (p1);
  system.out.println (STR1);
  
 }

}
The test output is as follows:
gu 123456 male
name:gu
num:123456
Sex:male
age:24
{"Age": "Name": "Gu1", " Num ": 123," sex ":" Male "}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.