问题描述
我正在尝试将 Java 项目转换为 C#。在下面的文章中,我不知道如何转换 Json 部分。
Cursor resultSet = helper.openDataBase().rawQuery("Select * from word where wname=?",new String[] {String.valueOf(editable)});
TextView TextView_FA = findViewById(R.id.textView_FA);
if( resultSet.movetoFirst())
{
String str_json = resultSet.getString(2);
try {
JSONObject obj = new JSONObject(str_json);
String trans = obj.getJSONArray("ss").optJSONObject(0) .getString("s");
TextView_FA.setText(trans);
} catch (JSONException e) {
TextView_FA.setText(e.getLocalizedMessage());
}
}
else {
TextView_FA.setText("no translation found");
}
这是我试过的:
EditText EditText_en = FindViewById<EditText>(Resource.Id.EditText_en);
Java.IO.File fil = new Java.IO.File(db_src);
sqliteDatabase db = sqliteDatabase.OpenDatabase(fil,null);
Android.Database.ICursor resultSet = db.RawQuery("Select * from word where wname =? ",new[]{ EditText_en.Text});
TextView TextView_FA = FindViewById<TextView>(Resource.Id.TextView_fa);
if (resultSet.MovetoFirst())
{
String str_json = resultSet.GetString(2);
try
{
// JSONObject obj = new JSONObject(str_json);
// String trans = obj.getJSONArray("ss").optJSONObject(0).getString("s");
TextView_FA.Text = trans;
}
catch (Exception e)
{
TextView_FA.Text = e.Message;
}
}
else
{
TextView_FA.Text = "no translation found" ;
}
我评论的两行是问题。 我尝试使用 System.Text.Json 或 System.Json 作为一些互联网文档所说的但 VS2019 智能感知无法将它们识别为有效的库。
解决方法
要使用 NewtonSoft.JSon,我可能是反序列化 json 的最常用方法,并且比 System.Text.Json 更容易(宽容)。如果您有已知类型,使用 JSon 也更容易。我不知道你的 JSon 字符串是什么样子,但我已经制作了自己的示例字符串
lockheed:jerunh simon$ gnatmake main.adb -gnat95 -f
gcc -c -gnat95 main.adb
gcc -c -gnat95 foo.adb
gnatbind -x main.ali
gnatlink main.ali
lockheed:jerunh simon$ ./main
lockheed:jerunh simon$
如果你有一个类或者可以定义它,那么使用 JSon 会更容易,但是我创建了一个没有使用类的示例
//[
// {
// color: "red",// value: "#f00"
// },// {
// color: "green",// value: "#0f0"
// },// {
// color: "blue",// value: "#00f"
// }
//]
string myJson = "[\r\n\t{\r\n\t\t\"color\": \"red\",\r\n\t\t\"value\": \"#f00\"\r\n\t},\r\n\t{\r\n\t\t\"color\": \"green\",\r\n\t\t\"value\": \"#0f0\"\r\n\t},\r\n\t{\r\n\t\t\"color\": \"blue\",\r\n\t\t\"value\": \"#00f\"\r\n\t}\r\n\t\r\n]";
NewtonSoft 和 System.Text.Json 的示例
public class custColor
{
public string color { get; set; }
public string value { get; set; }
}